Home >Web Front-end >JS Tutorial >How Do I Use the \'addEventListener\' Method in Internet Explorer 9?
Question:
When dealing with event handling in Internet Explorer 9, what is the appropriate equivalent to the Element Object's addEventListener method?
Answer:
Internet Explorer 9 introduced the standardized addEventListener method, which is universally adopted as the preferred technique for handling events in web development.
Internet Explorer's Legacy Event Handling
Prior to Internet Explorer 9, Internet Explorer utilized the non-standard attachEvent approach instead of addEventListener. Here's an example of how it works:
elem.attachEvent("on" + evnt, func);
Unifying Event Handling Across Browsers
To create a cross-browser compatible event handling function, the following approach can be used:
function addEvent(evnt, elem, func) { if (elem.addEventListener) // W3C DOM elem.addEventListener(evnt, func, false); else if (elem.attachEvent) { // IE DOM elem.attachEvent("on" + evnt, func); } else { // No much to do elem["on" + evnt] = func; } }
This function effectively translates the desired event (evnt), element (elem), and function to be executed (func) into a cross-browser compatible event handling implementation.
The above is the detailed content of How Do I Use the \'addEventListener\' Method in Internet Explorer 9?. For more information, please follow other related articles on the PHP Chinese website!