我正在尝试为一组复选框获取一串ID.下面的代码确实包含ID,但它也包含空格和双重逗号,用于未选中的复选框.
有没有办法获得一串只有ID?
谢谢!
$($('input[type=checkbox][name=selector]')).each(function () {
var sThisVal = (this.checked ? this.id : "");
sList += (sList == "" ? sThisVal : "," + sThisVal);
});
Run Code Online (Sandbox Code Playgroud)
您可以使用map()来获取已选中复选框的逗号分隔ID
strIds = $('input[type=checkbox][name=selector]').map(function () {
if(this.checked) return this.id;
}).get().join(',');
Run Code Online (Sandbox Code Playgroud)
通过简化选择器并使选择器返回选中的复选框,使用:checked selector,使其变得简单.
strIds = $('[name=selector]:checked').map(function () {
return this.id;
}).get().join(',');
Run Code Online (Sandbox Code Playgroud)