-1

我有这个代码:

function gatherFollowers() {
            var followers = [];
            jQuery('.follower').each(function(index, value) {
                var i = parseInt(jQuery(this).attr('data-id'));
                followers.push(i);
            });
            return followers;
        }

那应该抓住所有属性,但结果它返回:

[100, 99, 88, 72, 63, 34, 31, 30, 29, each: function, eachSlice: function, all: function, any: function, collect: function…]

我怎样才能让它返回这样的简单数组:

[4,29,30,31,32,34,36,37,60,61,63,72,76,77,88,99,100] 

谢谢

4

4 回答 4

4

我相信你可以使用map()来获得你需要的东西 - 和 .get()

function gatherFollowers() {
    return jQuery('.follower').map(function(i,v){
        return $(v).data('id');
    }).get();
}

小提琴

于 2013-03-11T19:54:49.777 回答
1

尝试

function gatherFollowers() {
    var followers = $.map($('.follower'), function(value) {
        return parseInt($(this).data('id'), 10);
    });

    // followers should be an array of numbers
}

我已将您的代码更改为使用$.map以及.data()用于访问 HTML 5 数据id属性。

于 2013-03-11T19:51:48.000 回答
0

好吧,实际上将这个函数结果推入对象确实帮助了我 followers.data = gatherFollowers();

现在 console.log 显示

Object {data: Array[9], type: "custom"}
data: Array[9]
0: "100"
1: "99"
2: "88"
3: "72"
4: "63"
5: "34"
6: "31"
7: "30"
8: "29"
length: 9
__proto__: Array[0]
type: "custom"

正如预期的那样。

于 2013-03-12T15:04:00.810 回答
0

我试过这个:

//HTML
//<div id="1" class="follower">follower1</div>
//<div id="2" class="follower">follower2</div>

var followers = [];
$('.follower').each( function(index, value){
    var follower_id = $('.follower:eq(' + index + ')').attr('id');
    followers.push(follower_id)
});
console.log(followers)
//output [1,2]
于 2016-03-23T16:25:19.483 回答