【发布时间】: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