Add multiple ids in getElementById [duplicate]

三世轮回 提交于 2019-12-09 22:34:41

问题


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

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

回答1:


You can use querySelectorAll to select many items by their IDs:

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.




回答2:


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

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.




回答3:


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

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.

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.

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



来源:https://stackoverflow.com/questions/33798707/add-multiple-ids-in-getelementbyid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!