60

¿Cuál es el equivalente al Element Object en Internet Explorer 9?addEventListener en Internet Explorer

if (!Element.prototype.addEventListener) { 
    Element.prototype.addEventListener = function() { .. } 
} 

¿Cómo funciona en Internet Explorer?

Si hay una función igual a addEventListener y no lo sé, explique por favor.

Cualquier ayuda sería apreciada. Siéntase libre de sugerir una forma completamente diferente de resolver el problema.

+0

Si un navegador implementa un prototipo de esquema de herencia para sus objetos DOM no es relevante si es compatible con W3C [EventTarget interface] (http://www.w3.org/TR/DOM-Level-2-Events/events .html # Events-EventTarget-addEventListener). Si desea probar el soporte, pruébelo directamente: 'if (element.addEventListener) {/ * supported * /} else {/ * not supported * /}' es efectivo en todos los navegadores y es independiente de la implementación. – RobG

Respuesta

131

addEventListener es el método DOM correcta de usar para la fijación de controladores de eventos.

Internet Explorer (hasta la versión 8) utilizó un método alternativo attachEvent.

Internet Explorer 9 admite el método adecuado addEventListener.

Lo siguiente debe ser un intento de escribir una función de addEvent cross-browser.

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[evnt] = func; 
    } 
} 
+18

La última condición también debe incluir '" on "+'. –

+69

Para IE9 y addEventListener necesita un HTML5 pcunite

+1

@pcunite. Deseo poder votar ese comentario más. Punto muy importante – Okeydoke

1

addEventListener es compatible desde la versión 9 en adelante; para versiones anteriores, utilice la función attachEvent algo similar.

2

Como dijo Delan, desea utilizar una combinación de addEventListener para las versiones más nuevas y attachEvent para las más antiguas.

Encontrará más información sobre los oyentes de eventos en MDN. (Tenga en cuenta que hay algunas advertencias con el valor de 'esto' en su oyente).

También puede usar un marco como jQuery para abstraer el manejo del evento por completo.

$("#someelementid").bind("click", function (event) { 
    // etc... $(this) is whetver caused the event 
}); 
16

John Resig, autor de jQuery, presentó su versión de la aplicación a través del navegador de addEvent y removeEvent para eludir los problemas de compatibilidad con IE inadecuada o inexistente addEventListener.

function addEvent(obj, type, fn) { 
    if (obj.attachEvent) { 
    obj['e'+type+fn] = fn; 
    obj[type+fn] = function(){obj['e'+type+fn](window.event);} 
    obj.attachEvent('on'+type, obj[type+fn]); 
    } else 
    obj.addEventListener(type, fn, false); 
} 
function removeEvent(obj, type, fn) { 
    if (obj.detachEvent) { 
    obj.detachEvent('on'+type, obj[type+fn]); 
    obj[type+fn] = null; 
    } else 
    obj.removeEventListener(type, fn, false); 
} 

Fuente: http://ejohn.org/projects/flexible-javascript-events/

+0

Este código intenta vincular la devolución de llamada fn a obj además de agregar un detector de eventos, pero esto es redundante porque todos los que usan JS ya deberían saber sobre 'esto'. –

+3

Habría obtenido más votos si hubiera presentado a John Resig como autor de ** jQuery **. –

+0

buen punto, actualizado – jchook

13

estoy usando esta solución y funciona en IE8 o superior.

if (typeof Element.prototype.addEventListener === 'undefined') { 
    Element.prototype.addEventListener = function (e, callback) { 
     e = 'on' + e; 
     return this.attachEvent(e, callback); 
    }; 
    } 

Y luego:

<button class="click-me">Say Hello</button> 

<script> 
    document.querySelectorAll('.click-me')[0].addEventListener('click', function() { 
    console.log('Hello'); 
    }); 
</script> 

Esto funciona tanto IE8 y Chrome, Firefox, etc.

+0

Tengo un problema con Element (type is undefined) – zchpit

+0

compruebe su versión de tipo de documento, este debe ser html5 doctype – Teobaldo

1

EDITAR

me escribió un fragmento que emulan la interfaz EventListener y el IE8 uno, es exigible incluso en objetos lisos: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

vieja respuesta

esta es una manera de addEventListener emular o attachEvent en navegadores que no son compatibles con uno de esos
esperanza ayudará

(function (w,d) { // 
    var 
     nc = "", nu = "", nr = "", t, 
     a = "addEventListener", 
     n = a in w, 
     c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","")), 
     u = n?(nu = "attach", "add"):(nu = "add","attach"), 
     r = n?(nr = "detach","remove"):(nr = "remove","detach") 
/* 
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener" 
*/ 
    function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture()) : capt ))}} 
    w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener] 
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener] 

})(window, document) 
1

Aquí hay algo para aquellos que gustan de código hermoso.

function addEventListener(obj,evt,func){ 
    if ('addEventListener' in window){ 
     obj.addEventListener(evt,func, false); 
    } else if ('attachEvent' in window){//IE 
     obj.attachEvent('on'+evt,func); 
    } 
} 

Shamelessly robado Iframe-Resizer.