Javascript - IE8 alternative to bind()

Javascript - IE8 alternative to bind()

本文关键字:bind to alternative IE8 Javascript      更新时间:2023-09-26
img.attachEvent("onclick", function(img){
 alert(img.id);
}.bind(null,img)); 

如何在IE 8中完成这项工作?或者最直接的选择是什么?

我在这里找到了一个填充物。

Function.prototype.bind = Function.prototype.bind || function(b) {
    if (typeof this !== "function") {
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var a = Array.prototype.slice;
    var f = a.call(arguments, 1);
    var e = this;
    var c = function() {};
    var d = function() {
      return e.apply(this instanceof c ? this : b || window, f.concat(a.call(arguments)));
    };
    c.prototype = this.prototype;
    d.prototype = new c();
    return d;
};

使用 event.srcElement

img.attachEvent("onclick", function(ev){
    alert(ev.srcElement.id);
});
我会给你一个JSFiddle

,但是JSFiddle在IE8中失败了。

编辑:另一种解决方案将使用闭包/变量解决方案。 像这样:

(function(){
    var _img=img;
    _img.attachEvent("onclick",function(ev){
        alert(_img.id);
    });
})();

这将创建img的本地副本,以便您可以在事件侦听器中使用它。

除此之外,我的建议是完全忘记IE 8。 (J/K(

我想添加这个作为评论,但让我发帖。 ">请使用jQuery,节省您解决此类问题的时间。

如果碰巧在不久的将来使用jQuery

$(document).on('click', '.class', function() {
    // code here
});

下面的这个页面上有一个很好的compatability脚本。只需将其复制并粘贴到脚本中即可。http://dochub.io/#javascript/function.bind