Javascript 在 getElementById 中添加多个 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33798707/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:29:30  来源:igfitidea点击:

Add multiple ids in getElementById

javascriptgetelementbyid

提问by Sam Provides

How to use this script with multiple ids? Does not work on the second id that I try to add

如何使用具有多个 ID 的脚本?不适用于我尝试添加的第二个 ID

<script type="text/javascript">
window.onload = (function () {
var elem = document.getElementById("id1","id2").onclick = function()
{
fbq('track', 'InitiateCheckout');
}
});
</script>

回答by Yeldar Kurmangaliyev

You can use querySelectorAllto select many items by their IDs:

您可以使用querySelectorAll它们的 ID 来选择许多项目:

var items = document.querySelectorAll('#id2, #id3, #id5');

for (var i = 0; i < items.length; i++)
{
  items[i].onclick = function() { 
    this.innerText = this.innerText + '!';
  };
}
2, 3, 5 are working:

<p id="id1">I am 1</p><p id="id2">I am 2</p><p id="id3">I am 3</p><p id="id4">I am 4</p><p id="id5">I am 5</p>

However, creating a common class sounds much better.

但是,创建一个公共类听起来要好得多。

回答by luschn

getElementById only takes one ID, but you can do this to select more than one element:

getElementById 只需要一个 ID,但您可以这样做来选择多个元素:

document.querySelectorAll('#id1, #id2');

...but you should not use that to create an event listener for every element. Better create one event listener for the whole document instead, for example:

...但您不应该使用它来为每个元素创建一个事件侦听器。最好为整个文档创建一个事件侦听器,例如:

document.addEventListener('click', handleClickEvents, false);

function handleClickEvents(evt) {
    myEventTarget = event.target;

    if (myEventTarget.id === 'id1') {

    } else if (myEventTarget.id === 'id2) {

    }
}

...or even better, use a framework like React or Angular.

...或者更好的是,使用像 React 或 Angular 这样的框架。

回答by Christos

The getElementByIdtakes only one parameter, the id of the element you want to select. You can't pass to id more than one ids.

getElementById只需要一个参数,你要选择的元素的ID。您不能传递给 id 多个 id。

For more documentantion on this, please have a look here.

有关这方面的更多文档,请查看此处

If you want to select multiple elements and attach to them the same event handler, you can use another approach.

如果要选择多个元素并将相同的事件处理程序附加到它们,则可以使用另一种方法。

First you have to add the same class to each of them, for instance js-classname.

首先,您必须为每个类添加相同的类,例如 js-classname。

Then you can select them using the method getElementsByClassName. This method will return to you an array like object containing all the elements with the class you specified.

然后您可以使用 方法选择它们getElementsByClassName。此方法将返回给您一个类似对象的数组,其中包含您指定的类的所有元素。

If you need more information about this, please have a look here.

如果您需要更多关于此的信息,请查看此处