在列表中的ID获得多个元素与jQuery

在列表中的ID获得多个元素与jQuery

问题描述:

我有我的HTML在列表中的ID获得多个元素与jQuery

<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 1234 2345 3456#1234 #2345 #3456
的名单我想获得其ID是在列表中的所有元素ID列表

我尝试$(":checkbox").attr('id', items_id);var items_cb = $(":checkbox[id='items_id']");其中items_id是项目列表,但它不工作

+1

CSS ID不能以数字开头,则应该将其更改为以字母开头 – Clive

只是尽量把所有的ID中选择以逗号分隔:

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

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

附:身份证不应以数字开头。

+0

谢谢你,它的工作原理 – Snote

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

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

...应该工作。

http://api.jquery.com/multiple-selector/

试试这个

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

可以使用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 
}); 

你可以建立一个选择符,如:

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

,那么你可以使用selectorString为:

$(selectorString) 

选择它们。

+0

我相信'id'应该是'i'。 –

+0

不,我应该是id :) – kommradHomer

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);