我收到此错误:
Uncaught TypeError: Cannot call method 'getAttribute' of undefined
从此代码( http://pastebin.com/Lrv8JfWK ):
<script type="text/javascript">
// Wait until page is done loading
window.onload = function()
{
var inputTagObjects = document.getElementsByTagName("input");
var inputTagDefaultValues = new Array();
for(var i = 0; i < inputTagObjects.length; i++)
{
// Only add input elements with a type and name attribute
if(inputTagObjects[i].hasAttribute("type") && inputTagObjects[i].getAttribute("type") == "text" && inputTagObjects[i].hasAttribute("name"));
{
// Make sure the input element has a default value
if(inputTagObjects[i].hasAttribute("value") == false)
{
// Give an empty value attribute
inputTagObjects[i].setAttribute("value","");
}
// Assign default value to global array with the index of the input elements name
inputTagDefaultValues[inputTagObjects[i].name] = inputTagObjects[i].value;
// Assign Events
inputTagObjects[i].onfocus = function()
{
console.log(inputTagObjects[i].getAttribute("name") + " has been focused.");
}
inputTagObjects[i].onblur = function()
{
console.log(inputTagObjects[i].getAttribute("name") + " has been blurred.");
}
}
}
}
应该在聚焦时删除这些文本输入的值,如果模糊完成后没有输入任何内容,则重新填充它们。现在它应该只输出到控制台:
<body>
<div id="form">
<form method="post" enctype="multipart/form-data">
<p><input type="text" name="firstName" value="First Name" /></p>
<p><input type="text" name="lastName" value="Last Name" /></p>
</form>
</div>
</body>
为什么我会收到此错误以及如何修复它(不使用 JQuery)?
最佳答案
调用事件处理程序时,i
未设置为与分配时相同的值。
尝试在处理函数中将 inputTagObjects[i]
替换为 this
。
编辑:话又说回来,你不应该为此使用 JavaScript。以下是呈现表单的更好方法的建议:
<p><label>First name: <input type="text" name="firstName" placeholder="John" /></label></p>
<p><label>Last name: <input type="text" name="lastName" placeholder="Smith" /></label></p>
关于javascript - "Uncaught TypeError: Cannot call method ' getAttribute ' of undefined"来自 getElementsByTagName 对象的引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17799673/