我想问的是,当我在 jQuery 中使用字符串构建进行 .each
循环时:
$('.list :checkbox').each(function()
{
var type = $(this).attr('value');
Build += type + ', ';
return Build;
});
但现在我需要删除最后一个“,”(不带引号),因为它会生成如下列表:
Item 1, Item 2, Item 3, Item 4, Item 5,
然后必须将其添加到 html()
函数中,该函数运行良好,但是当尝试删除最后一个“,”时,这样做不起作用:
Build.substr(-1);
$('#list-box').html(Build);
但这行不通。
最佳答案
你可以用这样的东西简化你的代码:
(已更新)
var arr = $(":checkbox").map(function() {
return this.value;
}).get();
$('#list-box').html(arr.join(","));
在这里试试:http://jsfiddle.net/andrewwhitaker/rXB2K/ (也已更新)
关于JavaScript 变量的 jQuery html() 上的 JavaScript substr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4527437/