1

我收到此错误:

未捕获的类型错误:无法调用未定义的方法“getAttribute”

从此代码(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)?

4

1 回答 1

1

调用事件处理程序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>
于 2013-07-23T00:38:43.553 回答