2011-11-29 181 views
9

我有我的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

回答

12

只是儘量把所有的ID中選擇以逗號分隔:

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

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

附:身份證不應以數字開頭。

+0

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

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 
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爲:

$(selectorString) 

選擇它們。

+0

我相信'id'應該是'i'。 –

+0

不,我應該是id :) – 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);