gpt4 book ai didi

javascript - 尝试使用 vanilla JS 创建一个 each 方法,就像在 jQuery 中一样

转载 作者:数据小太阳 更新时间:2023-10-29 04:33:34 24 4
gpt4 key购买 nike

Element.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) {
fn(i);
}
};

var li = document.getElementsByTagName('li');

li.each(function(i) {
this.style.borderBottom = '1px solid red';
});

我正在尝试制作一个类似于 jQuery 中的 each 方法。我在 for 循环和回调中尝试了很多东西,但我遇到了错误。我确定这与“this”上下文有关。

最佳答案

您可以使用调用来设置上下文

编辑:Element 不是正确的类,它应该是 NodeListHTMLCollection

NodeList.prototype.each = HTMLCollection.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) {
fn.call(this, i);
}
};

当您使用 Function.prototype.call 时它允许您将上下文 AKA this 绑定(bind)到函数

AFAIK 有 3 种方法可以做到这一点:

  • call (如上所述)
  • apply (除了它只接受两个参数,第二个是一个数组,它的工作方式类似于调用)
  • bind (用于 currying )

另请注意,自 DOM level 4 (ES6 harmony) 起有一个名为 Elements 的新类,它扩展了 Array 并且旨在替换 NodeList/HTMLCollection,因此您不会不需要在 ES6 中实际扩展它以添加 each 方法并使用 Array.prototype.forEach相反(尽管您将无法在回调中使用 this

关于javascript - 尝试使用 vanilla JS 创建一个 each 方法,就像在 jQuery 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27544591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com