Javascript 通过javascript将事件侦听器附加到单选按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8922002/
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
Attach event listener through javascript to radio button
提问by Acn
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-
现在我必须通过 javascript 向所有单选按钮添加事件侦听器。如果下面的伪代码是错误的,那么请告诉我该怎么做-
var radios = document.forms["formA"].elements["myradio"];
for(radio in radios) {
radio.onclick = function() {
alert(radio.value);
}
}
回答by Adam Rackis
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:
JavaScript 中的 for in 循环返回键,而不是值。要让 for in 循环工作,假设您没有向数组添加自定义属性,您可以执行以下操作:
for(radio in radios) {
radios[radio].onclick = function() {
alert(this.value);
}
}
But you should alwaysloop an array with a regular for loop to avoid accidentally including custom-added enumerable properties:
但是您应该始终使用常规 for 循环来循环数组,以避免意外包含自定义添加的可枚举属性:
var radios = document.forms["formA"].elements["myradio"];
for(var i = 0, max = radios.length; i < max; i++) {
radios[i].onclick = function() {
alert(this.value);
}
}
回答by xbonez
You could add just a single listener that listens to all radio buttons, rather than individual listeners.
您可以只添加一个监听所有单选按钮的监听器,而不是单个监听器。
using jquery, you could do it like this
使用jquery,你可以这样做
$(document).ready(function(){
$('input[type=radio]').click(function(){
alert(this.value);
});
});
For only the radios within a form with id formA
仅适用于带有 id 的表单中的收音机 formA
$(document).ready(function(){
$('#formA input[type=radio]').click(function(){
alert(this.value);
});
});
For only radios with an id myradio
仅适用于带有 id 的收音机 myradio
$(document).ready(function(){
$('input[type=radio]').click(function(){
if (this.id == "myradio")
alert(this.value);
});
});
回答by RobG
A good start, but don't use for..in that way as it will iterate over all enumerable properties and you haven't checked to see if they all represent elements.
一个好的开始,但不要以这种方式使用 for.. ,因为它会遍历所有可枚举的属性,而您还没有检查它们是否都代表元素。
Much better to use an index:
使用索引要好得多:
for (var i=0, iLen=radios.length; i<iLen; i++) {
radios[i].onclick = function() {...};
}
回答by Diode
for(var property in object) { ... }
is used to loop in objects to find properties. for array you can use normal for loop
用于在对象中循环以查找属性。对于数组,您可以使用普通的 for 循环
for(var i=0; i< radios.length; i++) {
var radio = radios[i];
....
}
回答by KyleMit
Another option is to attach multiple elements to a single event listenerby using delegated handlers
另一种选择是使用委托处理程序将多个元素附加到单个事件侦听器
You can attach the parent listener to document
or any appropriate parent node. Then you can check the event was raised by the appropriate target using the Element.matches()
API or anything on event.target
您可以将父侦听器附加到document
或任何适当的父节点。然后,您可以使用Element.matches()
API 或上的任何内容检查由适当目标引发的事件event.target
document.getElementById("languages").addEventListener('click', function (event) {
if (event.target && event.target.matches("input[type='radio']")) {
// do something here ...
}
});
This is roughly equivalent to the following jQuery syntax which uses .on()
to provide delegation
这大致相当于以下.on()
用于提供委托的jQuery 语法
$("#languages").on("click", "input[type='radio']", function(event) {
// do something here ...
});
If you want to extend the EventTarget.addEventListener()
prototype, you can wrap with your own method:
如果你想扩展EventTarget.addEventListener()
原型,你可以用你自己的方法包装:
window.EventTarget.prototype.addDelegatedListener = function(type, delegateSelector, listener) {
this.addEventListener(type, function (event) {
if (event.target && event.target.matches(delegateSelector)) {
listener.call(event.target, event)
}
});
}
Then use like this:
然后像这样使用:
document.addDelegatedListener("click", "input[type='radio']", function(event) {
// do something here ...
});
Demo in Stack Snippets
堆栈片段中的演示
// example 1 - regular add event listener
document.getElementById("languages").addEventListener('click', function (event) {
if ( event.target && event.target.matches("input[type='radio']") ) {
console.log(event.target.value)
}
});
// example 2 - reusable delegated listener
window.EventTarget.prototype.addDelegatedListener = function(type, delegateSelector, listener) {
this.addEventListener(type, function (event) {
if (event.target && event.target.matches(delegateSelector)) {
listener.call(event.target, event)
}
});
}
let parent = document.getElementById("weekdays")
parent.addDelegatedListener("click", "input[type='radio']", function(event) {
console.log(this.value)
});
h3 {
margin-top: 20px;
margin-bottom: 10px;
font-size: 1.1em;
}
code {
background: #e9e9e9;
padding: 1px 4px;
border-radius: 3px;
}
label input {
vertical-align: text-top;
}
<h3>Languages <code>addEventListener</code> + <code>Element.matches</code></h3>
<div id="languages">
<label><input type="radio" name="languages" value="HTML"> HTML </label>
<label><input type="radio" name="languages" value="JS"> JS </label>
<label><input type="radio" name="languages" value="CSS"> CSS </label>
</div>
<h3>Weekdays <code>EventTarget.prototype.addDelegatedListener</code></h3>
<div id="weekdays">
<label><input type="radio" name="days" value="Mon"> Mon </label>
<label><input type="radio" name="days" value="Tue"> Tue </label>
<label><input type="radio" name="days" value="Wed"> Wed </label>
</div>