【问题标题】:jQuery array .map inside .each.each 内的 jQuery 数组 .map
【发布时间】:2011-11-18 16:26:37
【问题描述】:

我在$.each 函数中有一个数组。我想遍历它来创建一个新的或修改过的数组。但我需要从外部$.each 循环访问$(this):

// target these data attributes:
$selector = $('[data-my0], [data-my1], [data-my2]');

$.each($selector, function() {        

    var $this = $(this), // cache selector
        keys = ['my0', 'my1', 'my2']; // array of data keys

    // I want to use the keys array to make a vals array to this:
    // var vals = [$this.data('my0'), $this.data('my1'), $this.data('my2')];

    // This doesn't seem to work (can't read from length 0 error):
    var vals = $.map( keys, function( key ) { return $this.data(key); });

}); 

我认为使用$.each 或$.map 可以做到这一点,但这是我被卡住的地方。我知道$(this) 不能正常与$.map 一起使用,就像$.each 一样。在这种情况下,我试图从代表选择器的外部传递$this。

【问题讨论】:

  • 不是问题的一部分,但你也可以写$selector.each(...)。
  • 我认为你的类型是);。
  • @pimvdb 是的,这也是一个问题,但它不会导致“无法从长度 0 读取”错误。我没有从代码中得到 the jsfiddle I did 中的错误。
  • @pimvdb 谢谢(这就是我必须在 5:30 起床并开车送妈妈去机场时发生的事情,哈哈)。

标签: javascript jquery arrays map each


【解决方案1】:

等等 - 你正在将“vals”传递给“$.map()”,而不是“keys”:

var vals = $.map( keys, function( key ) { return $this.data(key); });

Here 是一个 jsfiddle。代码工作得很好,虽然没有看到你的实际 HTML,很难确切地知道你期望发生什么。

【讨论】:

  • 这是好的和坏的 b/c 这意味着这有效,但我必须在其他地方遇到问题。谢谢你:)
  • 而 html 就像 <div data-my0='hello' data-my1='out' data-my2='there'></div> - 在小提琴中也是如此。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2013-09-28
  • 2021-09-20
  • 1970-01-01
  • 2013-12-29
  • 2014-04-26
  • 2011-03-01
  • 2013-08-02
  • 2015-09-14
相关资源
最近更新 更多