javascript 为具有相同 ID 的单选按钮添加事件监听器

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

addEventListener for Radio buttons with same id

javascript

提问by Rajesh

Is it possible to add events using addEventListenerto multiple radio buttons with same id ?

是否可以使用addEventListener多个具有相同 id 的单选按钮添加事件?

<input id="radId" type="radio" value="0" name="radioname">No
<input id="radId" type="radio" value="1" name="radioname">Yes

I tried to attach event using document.getelementByIDBUT it always picks the first radio button.

我尝试使用document.getelementByID但它总是选择第一个单选按钮附加事件。

Is there a way around this, any help would be highly appreciated.

有没有办法解决这个问题,任何帮助将不胜感激。

Thanks

谢谢

回答by Felix Kling

As others said, an ID has to be unique. You could get elements with getElementsByName(note that there are some issues) and iterate over them:

正如其他人所说,ID 必须是唯一的。您可以使用getElementsByName请注意存在一些问题)获取元素并对其进行迭代:

var handler = function() {
    //...
};

var radios = document.getElementsByName('radioname');

for(var i = radios.length; i--; ) {
    radios[i].onclick = handler;
}

Also note that addEventListenerdoes not exist in < IE8, there you have to use attachEvent. I suggest to read the excellent articles about event handling on quirksmode.org.

另请注意,addEventListener在 < IE8 中不存在,您必须使用attachEvent. 我建议阅读quirksmode.org 上关于事件处理优秀文章

回答by RobG

No, that is invalid. ID must be unique.

不,那是无效的。ID 必须是唯一的。

Well, you can if you can select the elements some other way - by class, tag, childNode, etc.

好吧,如果您可以通过其他方式选择元素 - 按类、标签、子节点等,您就可以。

回答by Carlos Javier Saldana

 var radiobuttonlist= document.querySelectorAll('#radId');
var radioButtonItems = [].slice.call(radiobuttonlist);

    radioButtonItems.forEach(function (item, idx) {
    item.addEventListener('change',YourFunction);});

回答by Fabio Sodre

Create array of the radio type elements and use forEach!

创建无线电类型元素的数组并使用 forEach!

<input type="radio" value="0" name="radioname">No
<input type="radio" value="1" name="radioname">Yes

<script>
//Load entire html document
window.addEventListener("load", function(){
   //Array elements radio
   var radioOption = [document.getElementsByName('radioname')[0],document.getElementsByName('radioname')[1]];
   //Use forEach
   radioOption.forEach(function(e) {
       e.addEventListener("click", function() {             
       alert(e.value);
       });
    });
});
</script>

回答by nope

dont use the same id for 2 elemetns, use classes. and then you can use something like this

不要对 2 个元素使用相同的 id,请使用类。然后你可以使用这样的东西

document.getElementsByClassName("whateverclass").onclick=function()