addEventListener not working in IE8

前端 未结 9 1453
耶瑟儿~
耶瑟儿~ 2020-11-22 15:40

I have created a checkbox dynamically. I have used addEventListener to call a function on click of the checkbox, which works in Google Chrome and Firefox but <

相关标签:
9条回答
  • 2020-11-22 15:47
    if (document.addEventListener) {
        document.addEventListener("click", attachEvent, false);
    }
    else {
        document.attachEvent("onclick", attachEvent);
    }
    function attachEvent(ev) {
        var target = ev.target || ev.srcElement;
        // custom code
    }
    
    0 讨论(0)
  • 2020-11-22 15:48

    You can use the below addEvent() function to add events for most things but note that for XMLHttpRequest if (el.attachEvent) will fail in IE8, because it doesn't support XMLHttpRequest.attachEvent() so you have to use XMLHttpRequest.onload = function() {} instead.

    function addEvent(el, e, f) {
        if (el.attachEvent) {
            return el.attachEvent('on'+e, f);
        }
        else {
            return el.addEventListener(e, f, false);
        }
    }
    
    var ajax = new XMLHttpRequest();
    ajax.onload = function(e) {
    }
    
    0 讨论(0)
  • 2020-11-22 15:58

    You have to use attachEvent in IE versions prior to IE9. Detect whether addEventListener is defined and use attachEvent if it isn't:

    if(_checkbox.addEventListener)
        _checkbox.addEventListener("click",setCheckedValues,false);
    else
        _checkbox.attachEvent("onclick",setCheckedValues);
    //                         ^^ -- onclick, not click
    

    Note that IE11 will remove attachEvent.

    See also:

    • MDN: element.addEventListener: Legacy Internet Explorer and attachEvent
    • MSDN: attachEvent method
    0 讨论(0)
  • 2020-11-22 16:01

    If you use jQuery you can write:

    $( _checkbox ).click( function( e ){ /*process event here*/ } )
    
    0 讨论(0)
  • 2020-11-22 16:04

    I've opted for a quick Polyfill based on the above answers:

    //# Polyfill
    window.addEventListener = window.addEventListener || function (e, f) { window.attachEvent('on' + e, f); };
    
    //# Standard usage
    window.addEventListener("message", function(){ /*...*/ }, false);
    

    Of course, like the answers above this doesn't ensure that window.attachEvent exists, which may or may not be an issue.

    0 讨论(0)
  • 2020-11-22 16:05

    Try:

    if (_checkbox.addEventListener) {
        _checkbox.addEventListener("click", setCheckedValues, false);
    }
    else {
        _checkbox.attachEvent("onclick", setCheckedValues);
    }
    

    Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.

    0 讨论(0)
提交回复
热议问题