javascript 使用 jQuery 通过 id 列表获取多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8308242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get multiple elements by a list of id's with jQuery
提问by Snote
I have that in my html
我的 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">
And an list of id 1234 2345 3456
or #1234 #2345 #3456
和一个 id 列表1234 2345 3456
或#1234 #2345 #3456
I want to get all the element of the list whose id is in the list of id
我想获取列表中所有 id 在 id 列表中的元素
I try $(":checkbox").attr('id', items_id);
and var items_cb = $(":checkbox[id='items_id']");
where items_id is the list of item, but it doesn't work.
我试着$(":checkbox").attr('id', items_id);
和var items_cb = $(":checkbox[id='items_id']");
其中items_id是项目的列表,但它不工作。
回答by Samich
Just try to put all id's in selector separated by comma:
只需尝试将所有 id 放入以逗号分隔的选择器中:
$('#1234, #2345, #3456')...
Code: http://jsfiddle.net/3df6W/
代码:http: //jsfiddle.net/3df6W/
P.S. ID's shouldn't start with digits.
PS ID 不应以数字开头。
回答by M S
Try this
试试这个
$('#1234, #2345, #3456')
回答by Piotr Kula
You can use the jQueryeach
method that will loop through all the selected elements.
您可以使用jQueryeach
方法循环遍历所有选定的元素。
HTML
HTML
<input name="myradio" type="checkbox" id="colour1">
<input name="myradio "type="checkbox" id="colour2">
<input name="myradio" type="checkbox" id="colour3">
JavaScript
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
});
回答by kommradHomer
you can just build a selector string like :
您可以构建一个选择器字符串,如:
var selectorString = '';
for id in idList:
selectorString = '#' + idList[id] + ',';
then you can use the selectorString as :
那么你可以使用 selectorString 作为:
$(selectorString)
to select them.
选择它们。
回答by thecodeparadox
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);
回答by wong2
var result = [];
for(var i=0; i < items_id.length; i++){
var id = items_id[i];
result.push($(id))
}
// result is what you want