addEventListener not working in IE8

前端 未结 9 1454
耶瑟儿~
耶瑟儿~ 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 16:05

    IE doesn't support addEventListener until version 9, so you have to use attachEvent, here's an example:

    if (!someElement.addEventListener) {
        _checkbox.attachEvent("onclick", setCheckedValues);
    }
    else {
        _checkbox.addEventListener("click", setCheckedValues, false);
    }
    
    0 讨论(0)
  • 2020-11-22 16:07

    This is also simple crossbrowser solution:

    var addEvent =  window.attachEvent||window.addEventListener;
    var event = window.attachEvent ? 'onclick' : 'click';
    addEvent(event, function(){
        alert('Hello!')
    });
    

    Instead of 'click' can be any event of course.

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

    Mayb it's easier (and has more performance) if you delegate the event handling to another element, for example your table

    $('idOfYourTable').on("click", "input:checkbox", function(){
    
    });
    

    in this way you will have only one event handler, and this will work also for newly added elements. This requires jQuery >= 1.7

    Otherwise use delegate()

    $('idOfYourTable').delegate("input:checkbox", "click", function(){
    
    });
    
    0 讨论(0)
提交回复
热议问题