带有Array的jQuery .each()

时间:2010-06-09 17:07:11

标签: jquery arrays each

基本上,我正在尝试使用特定类收集每个元素的ID,并将这些ID放入数组中。我正在使用jQuery 1.4.1并且已经尝试使用.each(),但是没有真正理解它或如何将数组传递出函数。

$('a#submitarray').click(function(){

    var datearray = new Array();

    $('.selected').each(function(){
        datearray.push($(this).attr('id'));
    });

    // AJAX code to send datearray to process.php file

});

我确信我已经离开了,因为我对此非常陌生,所以任何建议帮助都会很棒。谢谢!

6 个答案:

答案 0 :(得分:12)

您也可以使用map()

$('a#submitarray').click(function(){

  var datearray = $('selected').map(function(_, elem) {
    return elem.id;
  }).get(); // edited to add ".get()" at the end; thanks @patrick
  // ajax

});

map()方法将每个索引(我的示例不使用)和元素传递给给定函数,并根据返回值为您构建数组。

答案 1 :(得分:4)

尝试使用jquery的 map 功能:

datearray = $('.selected').map(function(){
    return $(this).attr('id');
}).get();

// use ajax to send datearray

答案 2 :(得分:1)

您不必将数组传递给匿名函数,因为它位于同一范围内。

答案 3 :(得分:1)

基于其他答案,这是一个简化版本:

var datearray = $('selected').map(function() {
  return this.id;
}).get();

map函数从每个元素获取id,get函数返回一个数组。在传递给map的匿名函数中,this依次引用每个选定的元素。

答案 4 :(得分:0)

IT对我来说都很好看,数组将被填充并在您放置评论的位置可用。对自己有信心。

答案 5 :(得分:0)

应该加载数组;您可以使用jQuery.post ...

将其发送到服务器
$.post("process.php", datearray, function(dat) {
  alert('Response: ' + dat);
});
相关问题