Javascript在循环中向eventListener函数传递参数
这段代码将把循环创建的最后一个值传递给eventListener函数,我需要附加创建eventListener时的值Javascript在循环中向eventListener函数传递参数,javascript,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(
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);
}
}
window.onload=function(){
var el=document.getElementsByClassName('modify');
对于(变量i=0;i
您可以通过使用生成器函数来实现:
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';
};
}
};
window.onload=函数(){
var el=document.getElementsByClassName('modify');
对于(变量i=0;i
makeHandler
返回的函数关闭id参数,该参数不会改变。您可以使用现代浏览器中所有函数上存在的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);
}
}
非常常见的问题,这里有一个解释:@MattGreer:使用闭包多年来一直是最佳实践,但在我看来,我们应该开始教人们使用
bind
,因为它是一个优秀的解决方案,很快就会内置到所有的浏览器中targeting@MartinJespersen酷,,我不知道你可以把args传给bind。我还没怎么用它,因为我们支持老年人。谢谢你的提醒。顺便说一句,第一个参数null是什么?第一个参数设置函数的这个值-因为你不需要特定的这个我将它设置为null-阅读提供的文档链接以完全理解函数
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;
};
}