0

我正在尝试为一组复选框获取一串 ID。下面的代码确实包含 ID,但它还包含空格和双逗号,用于未选中的复选框。

有没有办法只获取一串ID?

谢谢!

$($('input[type=checkbox][name=selector]')).each(function () {
       var sThisVal = (this.checked ? this.id : "");
       sList += (sList == "" ? sThisVal : "," + sThisVal);
});
4

1 回答 1

5

您可以使用map()获取选中复选框的逗号分隔 ID

strIds = $('input[type=checkbox][name=selector]').map(function () {                        
      if(this.checked) return  this.id;    
}).get().join(',');

通过简化选择器并使用:checked selector使选择器返回选中的复选框,使其变得有点简单。

strIds = $('[name=selector]:checked').map(function () {                        
       return  this.id;    
}).get().join(',');
于 2013-04-08T15:31:39.217 回答