【问题标题】:'this' inside each function in Prototype JSPrototype JS 中每个函数内的“this”
【发布时间】:2014-09-22 21:57:29
【问题描述】:

我正在尝试使用 example 选择器找到一个 div 元素,该选择器也具有代码中表示的 active 选择器。

使用 Prototype JS this 返回 windows.object 而不是单独的 div 本身。

如何让this 引用每个 div 元素以便我可以使用它?

$$('.example').each(function() {
    if(this.hasClassName('active')) {
        this.previous().setStyle({border:'1px solid #999'})
    }
});

【问题讨论】:

标签: javascript prototypejs this each


【解决方案1】:

http://api.prototypejs.org/language/Enumerable/prototype/each/

要访问该元素,您无需更改迭代器函数的上下文 (this)。迭代器函数接收项目作为第一个参数。您只需要命名参数即可。

$$('.example').each(function(div) {
    if(div.hasClassName('active')) {
        div.previous().setStyle({border:'1px solid #999'})
    }
});

此外,您可以通过更新传递给$$ 的 CSS 选择器来删除条件:

$$('.example.active').each(function(activeDiv) {
    activeDiv.previous().setStyle({border:'1px solid #999'})
});

如果您有兴趣在函数内部控制this 的值,请查看callapplybind

【讨论】:

  • 当使用 .each() 时,第二个参数将是上下文 - 因此在这种情况下,您将无法使用 bind(),但可以将 this 作为参数 2 传递给 .each()
猜你喜欢
  • 2013-12-01
  • 2014-02-20
  • 2018-03-28
  • 2016-01-08
  • 2011-05-15
  • 1970-01-01
  • 2016-04-21
  • 2011-06-09
  • 2011-06-16
相关资源
最近更新 更多