addEventListener alternative IE9

0

I have the following code and in IE9 I do not execute it ... What is the alternative to use?

 var but=document.createElement("button");
        but.className="action";
        but.innerHTML=ok[0];
        but.addEventListener('click',function(ev) {
            try{
             var divisi  = document.getElementById(id);            
             document.body.removeChild(divisi);
            }catch(Error){alert(Error);}
        });
    
asked by Iron Man 22.03.2018 в 11:17
source

1 answer

1

addEventListener is supported in IE9 (source: link )

  

[1]: attachEvent () is no longer supported in IE11 +.

     

EventTarget.addEventListener () is supported in IE9 +.

Anyway, if you want an alternative for previous versions you have to use attachEvent . Here is a small hack to use one or the other depending on the IE version:

var IE_version=document.documentMode;
if (navigator.appVersion.indexOf("Trident")!=-1){
document.write("<h2>Internet Explorer:" + IE_version + "</h2>");
} else {
document.write("<h2>No es una versión anterior a IE11</h2>");
}

alert(navigator.appVersion.indexOf("Trident")!=-1 && document.documentMode==8);

var but=document.createElement("button");
    but.className="action";
    but.innerHTML="Boton";
    addEvent('click',but,function(ev) {
        try{
         var divisi  = document.getElementById(id);            
         document.body.removeChild(divisi);
        }catch(Error){alert(Error);}
    });
  var d = document.getElementById("div");
  d.appendChild(but);
  
  
function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
{
  elem.addEventListener(evnt,func,false);
  alert("Estoy usando addEventListener");
  }
   else if (elem.attachEvent) { // IE DOM
  elem.attachEvent("on"+evnt, func);
  alert("Estoy usando attachEvent");
   }
   else { // No much to do
  elem[evnt] = func;
   }
}
<html>
<body>
<div id="div">
</div>
</body>
</html>

Source: link

    
answered by 22.03.2018 / 12:29
source