addEventListener en Internet Explorer


¿Cuál es el equivalente al Elemento Objeto en Internet Explorer 9?

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.

Author: The Mask, 2011-08-03

8 answers

addEventListener es el método DOM adecuado para usar para adjuntar controladores de eventos.

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

Internet Explorer 9 soporta el método apropiado addEventListener.

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

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;
   }
}
 132
Author: user278064,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-03 14:07:22

John Resig, autor de jQuery, presentó su versión de la implementación entre navegadores de addEvent y removeEvent para eludir los problemas de compatibilidad con addEventListener impropio o inexistente de IE.

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/

 16
Author: jchook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 14:44:34

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 funcionará tanto IE8 como Chrome, Firefox, etc.

 13
Author: Teobaldo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 03:24:36

Como dijo Delan, desea usar 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 'this' en su oyente).

También puede usar un framework como jQuery para abstraer el manejo de eventos por completo.

$("#someelementid").bind("click", function (event) {
   // etc... $(this) is whetver caused the event
});
 2
Author: phtrivier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-03 14:04:15

Aquí hay algo para aquellos que les gusta el 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);
    }
}

Descaradamente robado de Iframe-Resizer.

 2
Author: Eddie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-11 19:55:11

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

 1
Author: Delan Azabani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-03 13:58:51

EDITAR

Escribí un fragmento que emula la interfaz EventListener y la ie8, es llamable incluso en objetos planos: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

ANTIGUA RESPUESTA

Esta es una forma de emular addEventListener o attachEvent en navegadores que no admiten uno de esos
la 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
Author: asdru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-30 19:03:36

Usaría estos polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->
 0
Author: rofrol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-03 22:31:37