使用jQuery通过id列表获取多个元素

10

我在我的html中有这个

<input type="checkbox" id="1234">
<input type="checkbox" id="2345">
<input type="checkbox" id="3456">
<input type="checkbox" id="4567">
<input type="checkbox" id="5678">

我想要获取 id 列表中所有元素的内容。

我尝试使用 $(":checkbox").attr('id', items_id);var items_cb = $(":checkbox[id='items_id']");,其中 items_id 是 id 列表,但是它们并没有起到作用。

同时,id 列表的格式为 1234 2345 3456 或者 #1234 #2345 #3456


1
CSS的ID不能以数字开头,你应该将它们改为以字母开头。 - Clive
7个回答

14

尝试将所有ID用逗号分隔放在选择器中:

$('#1234, #2345, #3456')...

代码:http://jsfiddle.net/3df6W/

P.S. ID应该不以数字开头。


3

试试这个

$('#1234, #2345, #3456')

1
你可以使用 jQueryeach 方法,它将循环遍历所有选定的元素。
HTML
<input name="myradio" type="checkbox" id="colour1">
<input name="myradio "type="checkbox" id="colour2">
<input name="myradio" type="checkbox" id="colour3">

JavaScript

$('input:radio[name=myradio]').each(function (index) {
        alert(index + ': ' + $(this).val()); //is it checked?
        alert(index + ': ' + $(this).attr('id')); //ID string
        //You can compare if is this ID in items_id in this loop
});

1

你可以像这样构建一个选择器字符串:

var selectorString = '';
for id in idList:
    selectorString = '#' + idList[id] + ',';

如果你需要使用选择器字符串,那么你可以这样写:
 $(selectorString)

选择它们。


我认为 id 应该改为 i - Joshua Burns
不,应该是id而不是i :) - kommradHomer

1
var arr = ['1234', '2345', '3456'];
var elem = [];
$('body > input').filter(function() {
    if ($.inArray(this.id, arr) != -1) {
        elem.push({
            id: this.id,
            type: $(this).prop('type'),
            name: this.nodeName
        });
    }
});
console.log(elem);
console.log(elem.length);

0
var result = [];
for(var i=0; i < items_id.length; i++){  
    var id = items_id[i];
    result.push($(id))  
}
// result is what you want

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接