Hızlı yanıt: kod örneği
The method is the W3C standard method to attach an event handler to an element, so that you can do something useful when an event is triggered. The following example would popup an alert message when the element with id is clicked:Unfortunately this does not work in Internet Explorer, since Microsoft uses a different event registration model. In Internet Explorer 5+, you would have to attach the event handler as follows:Therefore for a cross browser event registration method, you can use reflection and execute conditionally:Further reading:
addEventListener
my_image_id
function doSomething() { alert('Image clicked');}var myImage = document.getElementById('my_image_id');myImage.addEventListener('click', doSomething, false);
myImage.attachEvent('onclick', doSomething);
function addEventHandler(node, type, f) { if (node.addEventListener) { node.addEventListener(type, f, false); } else if (node.attachEvent) { node.attachEvent("on" + type, f); } else { node["on" + type] = f; }}var myImage = document.getElementById('my_image_id');addEventHandler(myImage, 'click', doSomething);
- Mozilla Dev Center: element.addEventListener
- Quirksmode: Advanced event registration models
- Douglas Crockford: The Theory of the DOM