无法获取未定义或空引用的属性'options'

4

i am getting the above error in ie 10 please give me a suggestion.it is working fine in

function getSelectedIndex(element, value) {
    var selectedIndex = 0;
    for(i = 0; i < element.options.length; i++) {
        if(element.options[i].value == value) {
            selectedIndex = i;
            break;
        }
    }
    return selectedIndex;
}

element.options.length is giving Unable to get property 'options' of undefined or null reference.please suggest me a sample code. Edit : It was working for me when I was using IE11 with compatibility mode, but when I removed it and ran it in normal mode, the above issue occurred.


1
假设 element 是一个 <select>,为什么不使用 element.selectedIndex - Niccolò Campolungo
你怎么称呼这个函数? - XCS
他的问题在于加载实际元素。 - mavrosxristoforos
当我加载一个元素时,它会出现这个错误。 - user2814612
你的问题可能出现在以下三个地方之一:1)调用getSelectedIndex的位置;2)所需元素的HTML代码;3)脚本插入HTML的方式。 - Tibos
myform.freq.selectedIndex = getSelectedIndex(myform.freq, freqVal);他们正在这样调用 - user2814612
2个回答

2
使用 elements.options.indexOf(value) (假设element已定义,尽管它似乎没有被定义)。顺便说一下,您当前的设计将在第一个元素匹配或者根本没有匹配时返回零。如果您真的想编写自己的indexOf版本,在没有匹配的情况下最好返回-1

0

实际上,该消息会告诉您所需了解的一切。 您正在尝试读取某个没有值的属性,这里是“element”或“element.options”,请在函数调用之前检查它们设置的位置。 对于IE10,它是一个严格的版本,不支持使用element.options.length

相反,您应该使用:

document.getElementById("optionsID").value

希望这能有所帮助


我需要提到什么来翻译这个内容:element.options[i].value - user2814612

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接