Difference between element.event and element.setAttribute(event,handler)
For dyn开发者_如何学JAVAamically created elements I have noticed element.setAttribute(onClick,myFunction)
doesn't works properly in IE, whereas element.onclick=myFunction
works in all browsers. Are there any functional differences also apart from this browser difference?
In theory, setAttribute takes a string and assigns it to an attribute, this then gets mapped to any associated DOM properties. In IE 7 and lower (and in IE 8 in IE 7 compatibility mode and in Quirks mode), it assigns a value directly to a DOM property of the same name (rendering it case sensitive and useless when the property expects something other than a string value).
The onfoo series of DOM properties take a function.
It is generally preferred to use attachEventListener and friends instead, and to use an abstraction layer (such as provided by YUI, jQuery, etc) to assign the values. This is generally easier. Such libraries also tend to include features to work around memory leak related bugs.
精彩评论