简体   繁体   English

将多个getElementById语句合并为一个

[英]Combining multiple getElementById statements into one

I have a number of statement on a page that apply a click listener to a specific element identified with an ID. 我在页面上有很多语句,这些语句将点击侦听器应用于由ID标识的特定元素。 What would be the most efficient way to combine these into one statement? 将这些合并为一条语句的最有效方法是什么?

document.getElementById("foo1").addEventListener("click", function(){doSomething('bar1')});
document.getElementById("foo2").addEventListener("click", function(){doSomething('bar2')});
document.getElementById("foo3").addEventListener("click", function(){doSomething('bar3')});

You can write a wrapper that takes the id and the callback for the event listener and do something like this: 您可以编写一个包装,该包装接受事件侦听器的ID和回调,然后执行以下操作:

function addListenerToId(elemId, cb) {
    document.getElementById(elemId).addEventListener("click", cb);
}

And then: 接着:

addListenerToId('foo1', cb1);
addListenerToId('foo2', cb2);
addListenerToId('foo3', cb3);

Since the "foo" and "bar" are the same and all that changes is the number, we could just put it in a for loop! 由于“ foo”和“ bar”相同,并且所有更改都是数字,因此我们可以将其放入for循环中!

for(var i=1;i<=3;i++){
document.getElementById("foo"+i).addEventListener("click", function()
{doSomething('bar'+i)});
}

If you can't just do it with I as a number, you could make it a string first using the .toString() method. 如果不能只将I用作数字,则可以首先使用.toString()方法将其设置为字符串。 Hope this helps! 希望这可以帮助!

Make a for loop that iterates from 1 to the max number and when you use the id just add i to foo or bar : 进行一个从1到最大数字的for循环,当您使用id时,只需将i添加到foobar

for(let i = 1; i <= 3; i++)
{
    document.getElementById("foo" + i).addEventListener("click", function(){doSomething('bar' + id)});
}

Also if you only need to select all elements with id starting with foo for example you can use: 另外,例如,如果您只需要选择ID以foo开头的所有元素,则可以使用:

document.querySelectorAll("[id^='foo']").forEach((e) => {  
  e.addEventListener('click', doSomething);
});

You can use data-attributes to store the text and bind the click event to every element. 您可以使用data-attributes存储文本,并将click事件绑定到每个元素。

This is an example using a elements. 这是使用一个例子a元素。

 function doSomething(e) { e.preventDefault(); console.log(this.dataset.text); }; document.querySelectorAll('a').forEach((e) => { e.addEventListener('click', doSomething); }); 
 <a href="#" id="foo1" data-text="bar1">Foo1</a> <a href="#" id="foo2" data-text="bar2">Foo2</a> <a href="#" id="foo3" data-text="bar3">Foo3</a> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM