IE8中不支持addEventListener

时间:2014-05-02 05:09:11

标签: javascript internet-explorer-8

我为我的一个项目尝试过以下代码。此功能在单击另一个按钮时执行取消选中单选按钮。此代码适用于FF和chrome,但不适用于iE。请指教。

JS:

document.getElementById("main2").addEventListener("change", function(){
    if (this.checked) {
        var subs_list = document.getElementsByName("main_sub");
        var subs = Array.prototype.slice.call(subs_list);
        subs.forEach(function(sub){
            sub.checked = false;
        });
    }
});

var subs_list_2 = document.getElementsByName("main_sub");
var subs_2 = Array.prototype.slice.call(subs_list_2);
subs_2.forEach(function(sub){
    sub.addEventListener("change", function(){
        if (this.checked) {
            document.getElementById("main2").checked = false;
            document.getElementById("main").checked = true;
        }
    });
});

2 个答案:

答案 0 :(得分:2)

IE8不支持addEventListener()。它有自己的attachEvent()类似,所以你必须检查addEventListener是否存在,如果没有,请使用attachEvent()

IE8也不支持数组上的.forEach()。您可以为它安装垫片(显示为here),也可以使用常规for循环来迭代数组(以旧式方式)。

这是一个简单的跨浏览器事件函数:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}

所以,而不是:

sub.addEventListener("change", fn);

你会用这个:

addEvent(sub, "change", fn);

它可以在现代浏览器和旧版本的IE>

中使用

这是一个更高级的版本,具有更多功能:

// refined add event cross browser
function addEvent(elem, event, fn) {
    // allow the passing of an element id string instead of the DOM elem
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }

    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return(ret);
    }

    function attachHandler() {
        // normalize the target of the event
        window.event.target = window.event.srcElement;
        // make sure the event is passed to the fn also so that works the same too
        // set the this pointer same as addEventListener when fn is called
        var ret = fn.call(elem, window.event);   
        // support an optional return false to be cancel propagation and prevent default handling
        // like jQuery does
        if (ret === false) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        }
        return(ret);
    }

    if (elem.addEventListener) {
        elem.addEventListener(event, listenHandler, false);
    } else {
        elem.attachEvent("on" + event, attachHandler);
    }
}

答案 1 :(得分:0)

您可以改为使用attachEvent

另外,请参阅here以获取上面发布的答案。

这也是一个很好的答案,链接here