0

我正在尝试将所有循环结果合并为一个,然后使用 ajax 将它们全部发送一次

这是更多解释的代码:

<div class='item'>Name1</div>
<div class='item'>Name2</div>

jQuery

$(".item").each(function(){
  var value = $(this).text();
});

^ 这会同时返回 Name1 和 Name2 但不是一次,我需要将它们合并在一起,以便我可以将它们都发送到 ajax 请求

这就是我想要的(无效代码)

$(".item").each(function(){
  var value1 = $(this[0]).text(); // even tho i dont wanna use numbers, i wanna all of them
  var value2 = $(this[1]).text();
   var final = value1 + value2; // Name1Name2
});
    $.get('go.php', {items : final}, function(...

这是一个无效的代码 ^ 只是为了给你一个例子,它应该如何结束
第一个问题是合并,我不知道它应该如何,
第二个是我想从循环外部调用var final所以它不会重复请求

4

5 回答 5

0

Use $.map() to translate all elements in the jQuery object to an array of strings.

var values = $(".item").map(function() {
    return $(this).text();
}).get();
// values = ["Name1", "Name2"]

Alternatively, you can use jQuery.map().

var values = $.map($(".item"), function(item) {
    return $(item).text();
});
// values = ["Name1", "Name2"]

Then, you can either send the values as an array to your PHP script, so you can retrieve it as a PHP array in $_POST["items"].

$.get("go.php", {items : values}, function() { ... });

Or you can first join the array to a single string to receive it as a PHP string.

var joinedValues = values.join(",");
// joinedValues = "Name1,Name2"
$.get("go.php", {items : joinedValues}, function() { ... });
于 2012-06-04T15:25:26.120 回答
0

您可以使用$.map

var arr =  $(".item").map(function(){
             return $(this).text();
           }).get();

在这之后,你arr可以['Name1','Name2']随心所欲Name1Name2地得到它

arr.join('')

但是,如果您想稍后将它们分开,最好使用分隔符将它们连接起来_or ,。所以如果你想Name1_Name2使用.join('_')

然后arr像这样使用

$.get('go.php', {items : arr.join('_')}, function(...
于 2012-06-04T15:23:18.773 回答
0

在函数外部声明final以使其成为全局变量。

于 2012-06-04T15:23:21.417 回答
0

小提琴:http: //jsfiddle.net/iambriansreed/Wf3SF/

尝试:

var final = [];
$(".item").each(function(){
   final.push(this.innerHTML);
});

或者:

var final = $('.item').map(function() {
    return this.innerHTML;
}).get();

或者正如您在评论中提到的:

var items = $('.item').map(function() {
    return this.innerHTML;
}).get();

var final = "Something1" + items[0] + "Something2" + items[1];

或者最后像这样:

$('.item').each(function(i) {
    window['value'+(i+1)] = this.innerHTML;
});

var final = "Something1" + value1 + "Something2" + value2;

$.get('go.php', {'items' : final }, function(...
于 2012-06-04T15:23:33.507 回答
0
$('.item').text()​​;

这将Name1Name2作为输出返回。

现场演示

编辑:

在查看了您对所有答案的所有评论后,我了解到您可能正在寻找这个。

var customTextArray = [ "AAA", "BBB" ];
var final = "";
i = 0;
$('.item').each(function() {
    final += $(this).text();
    if (customTextArray.length != i)
        final += customTextArray[i++];

});

$(".result").text(final);​

输出:

Name1AAAName2BBBName3

参考另一个LIVE DEMO 2

于 2012-06-04T15:24:11.300 回答