Javascript 无法读取未定义的属性长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7158439/
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
Cannot read property length of undefined
提问by Praveen
I am trying to simply check if I have an empty input text box but I get this error when I run this in Chrome:
我试图简单地检查我是否有一个空的输入文本框,但是当我在 Chrome 中运行它时出现此错误:
Uncaught TypeError: Cannot read property 'length' of undefined.
未捕获的类型错误:无法读取未定义的属性“长度”。
Here is how I go about doing it. I check for DOM readiness and then call the function:
这是我如何去做。我检查 DOM 准备情况,然后调用函数:
function walkmydog() {
//when the user starts entering
if(document.getElementById('WallSearch').value.length == 0) {
alert("nothing");
}
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
采纳答案by GolezTrol
The id of the input seems is not WallSearch
. Maybe you're confusing that name
and id
. They are two different properties. name
is used to define the name by which the value is posted, while id
is the unique identification of the element inside the DOM.
输入的 id 似乎不是WallSearch
。也许你混淆了name
和id
。它们是两个不同的属性。name
用于定义发布值的名称,而id
是元素在 DOM 内部的唯一标识。
Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value
property.
另一种可能性是您有两个具有相同 id 的元素。浏览器将选择其中任何一个(可能是最后一个,也可能是第一个)并返回一个不支持该value
属性的元素。
回答by Lee
perhaps, you can first determine if the DOM does really exists,
或许,你可以先确定 DOM 是否真的存在,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}