按选项值过滤getElementsByTagName列表 [英] Filter getElementsByTagName list by option values
问题描述
我正在使用getElementsByTagName返回页面上的所有选择列表-然后可以根据选项值(即列表中第一项或第二项)过滤这些选择列表吗?
I'm using getElementsByTagName to return all the select lists on a page - is it possible to then filter these based upon an option value, ie of the first or second item in the list?
原因是出于某种原因,我将不去讨论这里,其中有一些带有数字值(1、2、3、4、5等)的选择列表,以及其他具有文本值(蓝色和黑色,红色)的选择列表和Black等),而我只希望脚本可以在带有数字值的脚本上运行.我不能向他们添加一个类,这会使我更容易做到这一点,但是我可以确定列表中的第一个选项值为"1".
The reason is that for reasons I won't go into here there are a block of select lists with number values (1,2,3,4,5 etc) and others which have text values (Blue and Black, Red and Black etc) and I only want the scripting I have to run on the ones with numerical values. I can't add a class to them which would more easily let me do this however I can be certain that the first option value in the list will be "1".
因此,有一种方法只能过滤那些第一个选项值为"1"的页面上返回的选择列表吗?
Therefore is there a way to filter the returned list of selects on the page by only those whose first option value is "1"?
推荐答案
我设法通过将一个简单的IF语句包装在要执行的操作(在本例中为禁用选项)周围来实现此目的,如下所示:
I managed to get this working by wrapping a simple IF statement around the action to be performed (in this case, disabling options) as follows:
inputs = document.getElementsByTagName('select');
for (i = 0; i < inputs.length; i++) {
if (inputs[i].options[1].text == 1) {
// perform action required
}
}
毫无疑问,这是一种更轻松或更经济的方法,但是最主要的是它对我有用.
No doubt there is a slicker or more economic way to do this but the main thing is it works for me.
这篇关于按选项值过滤getElementsByTagName列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!