通过javascript附加事件侦听器到单选按钮 [英] Attach event listener through javascript to radio button

查看:157
本文介绍了通过javascript附加事件侦听器到单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个同名的单选按钮。像这样:

 < form name =formA> 
< input type =radioname =myradiovalue =A/>
< input type =radioname =myradiovalue =B/>
< input type =radioname =myradiovalue =C/>
< input type =radioname =myradiovalue =D/>
< / form>

现在我必须通过javascript添加事件监听器到所有的单选按钮。如果以下伪代码错误,请告诉我如何做 -

  var radios = document.forms [formA ] .elements [ myradio]; 
(无线电收音机){
radio.onclick = function(){
alert(radio.value);
}
}


解决方案

JavaScript中的循环返回键,而不是值。要使for for循环工作,假设您尚未向数组添加自定义属性,您可以执行以下操作:

  for(radio in radioos){
radioos [radio] .onclick = function(){
alert(this.value);
}
}

但您应该始终 循环使用常规for循环的数组,以避免意外包括自定义添加的枚举属性:

  var radios = document.forms [ FORMA ]的元素[。myradio]; 
for(var i = 0,max = radios.length; i< max; i ++){
radios [i] .onclick = function(){
alert(this.value) ;
}
}


I have several radio buttons with the same name. Like this:

<form name="formA">
<input type="radio" name="myradio" value="A"/>
<input type="radio" name="myradio" value="B"/>
<input type="radio" name="myradio" value="C"/>
<input type="radio" name="myradio" value="D"/>
</form>

Now I have to add event listener through javascript to all the radio buttons. If the below pseudocode is wrong, then please tell me how to do it-

var radios = document.forms["formA"].elements["myradio"];
  for(radio in radios) {
    radio.onclick = function() {
        alert(radio.value);
    }
}

解决方案

For in loops in JavaScript return the keys, not the values. To get the for in loop to work, assuming you haven't added custom properties to your array, you'd do:

for(radio in radios) {
    radios[radio].onclick = function() {
        alert(this.value);
    }
}

But you should always loop an array with a regular for loop to avoid accidentally including custom-added enumerable properties:

var radios = document.forms["formA"].elements["myradio"];
for(var i = 0, max = radios.length; i < max; i++) {
    radios[i].onclick = function() {
        alert(this.value);
    }
}

这篇关于通过javascript附加事件侦听器到单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆