6

基本上,我试图收集具有特定类的每个元素的 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

});

我确定我已经走了,因为我对此很陌生,所以任何建议帮助都会很棒。谢谢!

4

6 回答 6

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()方法将每个索引(我的示例未使用)和元素传递给给定函数,并根据返回值为您构建一个数组。

于 2010-06-09T17:12:01.003 回答
4

试试jquery的map功能:

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

// use ajax to send datearray
于 2010-06-09T17:12:47.870 回答
1

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

于 2010-06-09T17:19:23.700 回答
1

在其他答案的基础上,这是一个简化版本:

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

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

于 2010-06-09T17:43:39.147 回答
0

应该加载数组;jQuery.post您可以使用...将其发送到服务器

$.post("process.php", datearray, function(dat) {
  alert('Response: ' + dat);
});
于 2010-06-09T17:23:56.667 回答
0

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

于 2010-06-09T17:11:45.137 回答