javascript 无法获取未定义或空引用的属性“选项”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19002022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to get property 'options' of undefined or null reference
提问by user2814612
i am getting the above error in ie 10 please give me a suggestion.it is working fine in
我在 ie 10 中遇到上述错误,请给我一个建议。它在
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.
element.options.length 给 Unable to get property 'options' of undefined or null reference.please 给我一个示例代码。编辑:当我在兼容模式下使用 IE11 时,它对我有用,但是当我删除它并在正常模式下运行时,出现了上述问题。
回答by user2814612
Use elements.options.indexOf(value)
(assuming element
is defined, which it doesn't seem to be). By the way, your current design will return zero if the first element matches orthere is no match at all. If you really want to write your own version of indexOf
, better to return -1
in the case of no match as it does.
使用elements.options.indexOf(value)
(假设element
已定义,但似乎并非如此)。顺便说一下,如果第一个元素匹配或根本不匹配,您当前的设计将返回零。如果您真的想编写自己的 版本indexOf
,最好-1
在不匹配的情况下返回。
回答by Labib Ismaiel
actually the message gives you exactly what you need to know.
you are trying to read a property of something that does not have a value, and here it is "element" or "element.options", check the place where they are set before the function call.
for IE10 it's a strict one, it doesn't support the use of
element.options.length
实际上,该消息为您提供了您需要知道的确切信息。您正在尝试读取没有值的属性,这里是“element”或“element.options”,请检查在函数调用之前设置它们的位置。对于 IE10,这是一个严格的,它不支持使用
element.options.length
instead you should use:
相反,您应该使用:
document.getElementById("optionsID").value
document.getElementById("optionsID").value
I hope this helps
我希望这有帮助