使用表格my_form
带有一组带有 name=my_radio
的单选按钮我可以得到 RadioNodeList
带有 my_form.elements.my_radio
的对象.我可以使用该对象的 value
获取当前选定按钮的值属性,如果我将字符串分配给 value
属性选定的选项会根据需要更改。
我希望能够做到my_form.elements.my_radio.addEventListener('change', ...
, 来监听值的变化(通过用户选择不同的选项),但它没有这样的方法。
如何检测值的变化?
是在每个单选按钮对象上设置事件监听器的唯一方法吗?
var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;
// This fails since RadioNodeList has no addEventListener function
/*
my_radio.addEventListener('change', function () {
console.log("Value changed; new value is " + my_radio.value);
});
*/
// The following works, but is there a better way, such as with a single event listener?
for (var i = 0, l = my_radio.length; i < l; i++) {
my_radio[i].addEventListener('change', function () {
console.log("Value changed; new value is " + my_radio.value);
});
}
<form id=my_form>
<div>
<label>
<input type=radio name=my_radio value=value_1>
Value 1
</label>
</div>
<div>
<label>
<input type=radio name=my_radio value=value_2>
Value 2
</label>
</div>
<div>
<label>
<input type=radio name=my_radio value=value_3>
Value 3
</label>
</div>
<div>
<label>
Some other field where I don't need to detect changes
<input name=some_other_field>
</label>
</div>
</form>
最佳答案
在您的标记中,仅将单选按钮包装在 fieldset
中.然后将事件监听器附加到那个而不是表单上,这样它就不会因为对其他 <input>
的更改而触发字段。
这是修改后的代码:
var my_form = document.querySelector('#my_form');
var my_radio = my_form.elements.my_radio;
var my_radio_group = document.querySelector('#my_radio_group');
// Attach the eventListener to the fieldset instead of the form
my_radio_group.addEventListener('change', function() {
// You actually don't even need the other global variables; this also works:
// let my_radio = this.form.elements.my_radio);
console.log("Value changed; new value is " + my_radio.value);
});
/* If you don't want any border around the radio group */
#my_radio_group {
border: none;
}
<form id="my_form">
<fieldset id="my_radio_group">
<div>
<label>
<input type="radio" name="my_radio" value="value_1">
Value 1
</label>
</div>
<div>
<label>
<input type="radio" name="my_radio" value="value_2">
Value 2
</label>
</div>
<div>
<label>
<input type="radio" name="my_radio" value="value_3">
Value 3
</label>
</div>
</fieldset>
<div>
<label>
Some other field where I don't need to detect changes
<input name="some_other_field">
</label>
</div>
</form>
为什么OP的第一种方法失败了
一个
RadioNodeList
, 是一种 NodeList
, 是节点的集合(在这种情况下是 radio 元素)。因此,它很像一个 JS 数组(你可以做 my_radio[i]
)。在 JS 中,事件只能被继承 EventTarget
的对象接收。接口(interface),像节点和 HTML 元素,而不是像数组和 NodeLists
这样的集合.要为多个元素附加单个事件处理程序,您必须将其附加到关闭父级并使用 Event Delegation .这是我在我的解决方案中所做的,使用
<fieldset>
元素。任何包装元素,例如<div>
就足够了;只是<fieldset>
这里在语义上更准确。
关于javascript - 如何检测 RadioNodeList 值的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154593/