简体   繁体   中英

difference between element.event and element.setAttribute(event,handler)

For dynamically created elements i have noticed element.setAttribute(onClick,myFunction) doesnt 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM