在.each循环中连接字符串

时间:2013-07-09 13:45:08

标签: javascript jquery string concatenation

这可能是一个愚蠢的问题,但我似乎无法得到它或在任何地方找到它。

我有一个.each函数,它返回页面上一堆div的id,然后为它们分配一个数字。我需要以特定的格式输出它们作为一个字符串,这样我就可以将它们传递给数据库并将它们用作“sort_order”值。 (我在数据库中通过一个sproc拆分它们。)

这是我的代码:

jQuery('#updateAllContentButton').click(function() {
    var count = 1;
 jQuery('.CommentaryItem').each(function() {
    var id = GetID(jQuery(this));
        var data_str = (id + ':' + count + '~');
        console.log(data_str);
        count++;
    });
});

因此,将每个data_str返回到一个单独的行,但我需要它返回如下: 144:2~145:3~146:4~147:4~148:5(等等)

任何帮助将不胜感激,谢谢!

4 个答案:

答案 0 :(得分:10)

使用map并加入:

jQuery('#updateAllContentButton').click(function() {
    console.log(jQuery('.CommentaryItem').map(function(i) {
        return GetID(jQuery(this)) + ':' + (i+1);
    }).get().join('~'));
});

请注意,您不必自己计算:大多数jQuery迭代函数都是为您完成的。

答案 1 :(得分:0)

您可以使用数组。像这样......

jQuery('#updateAllContentButton').click(function() {
    var count = 1;
    var arr = [];
 jQuery('.CommentaryItem').each(function() {
    var id = GetID(jQuery(this));
    var data_str = (id + ':' + count + '~');
    arr.push(data_str);
    //console.log(data_str);
    count++;
 });
 console.log(arr.join());
});

答案 2 :(得分:0)

试试这个:

jQuery('#updateAllContentButton').click(function() {
var count = 1;
var data_str = "";
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
    data_str += (id + ':' + count + '~');
    console.log(data_str);
    count++;
});

});

答案 3 :(得分:0)

变化

var data_str = (id + ':' + count + '~');

data_str+ = (id + ':' + count + '~');

完整代码

jQuery('#updateAllContentButton').click(function() {
    var count = 1,
        data_str;

    jQuery('.CommentaryItem').each(function() {
        var id = GetID(jQuery(this));
        data_str += (id + ':' + count + '~');
        console.log(data_str);
        count++;
    });
});