[英]Javascript pass parameter to eventListener function whilst in loop
This code will pass the last value created by the loop the eventListener function, I need the value at the time the eventListener was created to be attached. 这段代码将传递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);
}
}
You do that by using a builder function: 您可以使用构建器函数执行此操作:
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';
};
}
};
The function returned by makeHandler
closes over the theId
argument, which doesn't change. makeHandler
返回的函数将关闭theId
参数,该参数不会更改。
You can use the bind
prototype which exists on all functions in modern browsers 您可以使用现代浏览器中所有函数中存在的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);
}
}
If you need to support older browsers that doesn't have bind
nativly built in, you can use this poly-fill taken from MDN where you will also find documentation on the bind prototype function 如果您需要支持没有内置bind
旧浏览器,您可以使用从MDN获取的此poly-fill ,您还可以在其中找到有关绑定原型函数的文档
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;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.