下面的代码是 vanila JS 等价于 jQuery 的每个方法
NodeList.prototype.each = function(fn) {
for (var i = 0; i < this.length; i++) {
fn.apply(this[i], [i, this[i]]);
}
return this;
};
有人可以解释为什么使用参数索引“i”代码调用函数:fn.apply(this[i], [i, this[i]]);
下面的代码是 vanila JS 等价于 jQuery 的每个方法
NodeList.prototype.each = function(fn) {
for (var i = 0; i < this.length; i++) {
fn.apply(this[i], [i, this[i]]);
}
return this;
};
有人可以解释为什么使用参数索引“i”代码调用函数:fn.apply(this[i], [i, this[i]]);
TA贡献1570条经验 获得超10个赞
func.apply(thisArg, [argsArray]) :
thisArg:为调用func提供的this的值。
请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式代码中的函数,则 null 和 undefined 将被替换为全局对象,原始值将被装箱。此参数是必需的。
argsArray:可选 一个类似数组的对象,指定应调用 func 的参数,如果不应向函数提供参数,则指定 null 或 undefined。
就你而言:
this[i] 是属于 NodeList 的当前元素。
每个都是添加到 NodeList 的新函数您可以稍后使用,例如.querySelectorAll('p')
这是一个例子:
NodeList.prototype.each = function(fn) {
for (var i = 0; i < this.length; i++) {
console.log('this[' + i + ']=' + this[i].outerHTML);
fn.apply(this[i], [i, this[i]]);
}
return this;
};
document.querySelectorAll('p').each(function(idx, ele) {
console.log('each call: idx=' + idx + ' and ele=' + ele.outerHTML);
})
<p>1</p>
<p>2</p>
<p>3</p>
举报