无法读取未定义的属性长度
我试图简单地检查我是否有一个空的输入文本框,但当我在 Chrome 中运行此命令时出现此错误:
未捕获类型错误:无法读取未定义的属性“长度”。
以下是我的做法。我检查 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);
}
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:
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:
function walkmydog() {
//when the user starts entering
if(document.getElementById('WallSearch').value.length == 0) {
alert("nothing");
}
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
输入的 id 似乎不是
WallSearch
。也许您混淆了name
和id
。它们是两个不同的属性。name
用于定义发布值的名称,而id
是 DOM 内元素的唯一标识。另一种可能性是您有两个具有相同 id 的元素。浏览器将选择其中任何一个(可能是最后一个,也可能是第一个)并返回一个不支持
value
属性的元素。The id of the input seems is not
WallSearch
. Maybe you're confusing thatname
andid
. They are two different properties.name
is used to define the name by which the value is posted, whileid
is the unique identification of the element inside the 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.也许,你可以先确定 DOM 是否真的存在,
perhaps, you can first determine if the DOM does really exists,
我只是想针对这个问题提出另一个简单的解决方案。
I just wanted to throw out another simple solution to this problem.