I was looking for the most proper way to attach DOM events avoiding browser compatibility issues and found that the Mozilla developers site states:
The old way is to just assign it like this:
document.getElementById('cupcakeButton').onclick = getACupcake;
As above, the event object is either a global or an argument. This method may have problems and is not the preferred method, but it still works and a lot of people still use it.
What type of problems does this refer to?
The biggest problem I can think of is that it won't allow assigning multiple click handlers, by doing another .onclick = fn;
you basically unbind the previous handler if it was there.
Even if that magically worked, you would have no way to unregister a specific handler; it's all or nothing.
The most obvious one is already mentioned, it would replace a previously assigned handler .
document.getElementById('id')
should work in all browsers except in really old ones ( Netscape 4-
, IE 4-
) , there you should use document.layers['id']
and document.all[id]
respectively.
IE 5 up to IE 7
have one more issue , which is that they will also return elements where name='id'
instead of only the elements where id='id'
. That could really stuff you up.
Have a look at jQuery for a way to attach DOM event handlers avoiding browser compatibility issues.
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.