在循环中,Javascript将参数传递给addeventListener函数

时间:2013-08-31 18:25:27

标签: javascript

此代码将传递eventListener函数循环创建的最后一个值,我需要创建eventListener时附加的值。

window.onload = function() {

var el = document.getElementsByClassName('modify');

for (var i = 0; i < el.length; i++) {

     var getId=el[i].id.split("_");

     document.getElementById("modify_y_"+getId[2]).addEventListener('mouseover', function() {
     document.getElementById("modify_x_"+getId[2]).style.borderBottom = '#e6665 solid 3px';
    }, false); 

}
}

2 个答案:

答案 0 :(得分:1)

您可以使用构建器函数来执行此操作:

window.onload = function () {

    var el = document.getElementsByClassName('modify');

    for (var i = 0; i < el.length; i++) {

        var getId = el[i].id.split("_");

        document.getElementById("modify_y_" + getId[2]).addEventListener('mouseover', makeHandler(getId[2]), false);

    }

    function makeHandler(theId) {
        return function () {
            document.getElementById("modify_x_" + theId).style.borderBottom = '#e6665 solid 3px';
        };
    }
};

makeHandler返回的函数将关闭theId参数,该参数不会更改。

答案 1 :(得分:1)

您可以使用现代浏览器中所有功能中存在的bind原型

window.onload = function() {

var el = document.getElementsByClassName('modify');

for (var i = 0; i < el.length; i++) {

     var getId=el[i].id.split("_");

     document.getElementById("modify_y_"+getId[2]).addEventListener('mouseover', function(theid) {
       document.getElementById("modify_x_"+getId[2]).style.borderBottom = '#e6665 solid 3px';
    }.bind(null,getId[2]), false); 

}
}

如果您需要支持没有bind内置的旧版浏览器,可以使用此poly-fill taken from MDN,您还可以找到有关绑定原型函数的文档

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}