开发者

jQuery array .map inside .each

开发者 https://www.devze.com 2023-04-05 03:38 出处:网络
I have an array inside an开发者_如何转开发 $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:

I have an array inside an开发者_如何转开发 $.each function. I want to iterate through it to create a new or modified array. But I need to access the $(this) from the outside $.each loop:

// 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); });

}); 

I think it's possible to do this using using $.each or $.map but this is where I'm stuck. I know $(this) not used normally with $.map like it is with $.each. In this case, I'm trying to pass the $this from the outside that represents the selector.


Wait - you're passing "vals" into your "$.map()" cal instead of "keys":

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

Here is a jsfiddle. The code works just fine, though without seeing your actual HTML it's hard to know exactly what you expect to happen.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号