2013-11-26 17 views
-2

JavaScript代码的最后一行列出了我一个InvalidCharacterError,我想不通为什么:的Javascript给`invalidcharactererror`

var iCounter=0; 
var calendarText = document.createElement("input"); 
calendarText.setAttribute("SetAttribute(" + iCounter + ")", "onkeyup"); 

谁能告诉为什么?

+0

DO NOT使用SETATTRIBUTE添加事件。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener – epascarello

回答

3

属性名称不能包含()。您可以将其更改为

calendarText.setAttribute("SetAttribute_" + iCounter, "onkeyup"); 

如果使用自定义属性,请考虑使用data-* attributes

如果你只是通过在错误的顺序的参数,我只能建议总是read the documentation第一:

element.setAttribute(name, value);

但在这种情况下,你应该learn about the better ways to attach event handlers。例如。一个稍微好一点的办法是

calendarText.onkeyup = function() { 
    SetAttribute(i); 
}; 
2

它应该是

var iCounter=0; 
var calendarText = document.createElement("input"); 
calendarText.setAttribute("onkeyup", "SetAttribute(" + iCounter + ")"); 

的setAttribute方法的第二个参数是该属性的值(其是第一个)

elementNode.setAttribute(name,value) 
+0

抓住了参数顺序! –