您可以使用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
原生内置的旧浏览器,您可以使用从 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;
};
}