Pra*_*een 16 javascript dom javascript-events
我试图简单地检查我是否有一个空的输入文本框但是当我在chrome中运行时出现此错误:
Uncaught TypeError: Cannot read property 'length' of undefined.
Run Code Online (Sandbox Code Playgroud)
以下是我如何去做.我检查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);
}
Run Code Online (Sandbox Code Playgroud)
Gol*_*rol 10
输入的id似乎不是WallSearch.也许你这样的困惑,name和id.它们是两个不同的属性.name用于定义值的发布名称,同时id是DOM内部元素的唯一标识.
其他可能性是你有两个具有相同id的元素.浏览器将选择其中任何一个(可能是最后一个,也许是第一个)并返回不支持该value属性的元素.
也许,您可以先确定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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201388 次 |
| 最近记录: |