的getElementById - 多个ID [英] GetElementByID - Multiple IDs
本文介绍了的getElementById - 多个ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
这是不行的,所以我需要一个逗号或者分号,使这项工作?
This doesn't work, so do I need a comma or semi-colon to make this work?
推荐答案
的document.getElementById()
只支持一个名字在同一时间,只返回一个节点不是阵列节点。您有几种不同的选择:
document.getElementById()
only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
- 您可以实现自己的函数,它接受多个ID,并返回多个元素。
- 您可以使用<一个href=\"https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll\"><$c$c>document.querySelectorAll()$c$c>它允许你在一个CSS选择器字符串指定多个ID。
- 您可以把常见的类名的所有的节点上,并使用
document.getElementsByClassName()
用一个类名。
- You could implement your own function that takes multiple ids and returns multiple elements.
- You could use
document.querySelectorAll()
that allows you to specify multiple ids in a CSS selector string . - You could put a common class names on all those nodes and use
document.getElementsByClassName()
with a single class name.
每个选项的例子:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
或
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
或
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
这篇关于的getElementById - 多个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文