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

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

问题描述

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

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>

现在我必须通过javascript向所有单选按钮添加事件侦听器.如果下面的伪代码有误,请告诉我该怎么做-

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);
    }
}

推荐答案

JavaScript 中的 for in 循环返回键,而不是值.为了让 for in 循环工作,假设您没有向数组添加自定义属性,您应该这样做:

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);
    }
}

但是你应该总是用一个常规的 for 循环来循环一个数组,以避免意外地包含自定义添加的可枚举属性:

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天全站免登陆