多个单选按钮组的事件侦听器



你如何拥有一个动态的Javascript/JQuery事件侦听器来知道单击了哪个单选按钮组并检索选中元素的值。例如,如果我有两个单选按钮组,我怎么知道单击了哪个?对于动态数量的按钮组,我将如何执行此操作?

两个单选按钮组的示例:

<div class="btn-group btn-group-vertical" data-toggle="buttons">
     <input type="radio" name="input1" value="option1"/>
     <input type="radio" name="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
     <input type="radio" name="input2" value="option1"/>
     <input type="radio" name="input2" value="option2"/>
</div>

编辑:对于其他任何想知道以下以下哪个问题到目前为止"更"正确的人,两者都是正确的,因为.change(function(e) {.on('click', function(e) {的快捷方式

编辑2:删除了ID

要提供一个纯粹的 JavaScript 解决方案:为所有无线电类型输入创建一个集合,然后遍历所有输入,为每个输入添加一个事件侦听器。使用 this ,然后可以访问所需的任何属性或属性,如有必要,还可以访问父元素。

var inputs=document.querySelectorAll("input[type=radio]"),
    x=inputs.length;
while(x--)
    inputs[x].addEventListener("change",function(){
        console.log("Checked: "+this.checked);
        console.log("Name: "+this.name);
        console.log("Value: "+this.value);
        console.log("Parent: "+this.parent);
    },0);

或者,当您提到组的数量是动态的时,您可能需要一个活动节点列表,这需要一些额外的代码来检查input type

var inputs=document.getElementsByTagName("input"),
    x=inputs.length;
while(x--)
    if(inputs[x].type==="radio")
        inputs[x].addEventListener("change",function(){
            console.log("Checked: "+this.checked);
            console.log("Name: "+this.name);
            console.log("Value: "+this.value);
            console.log("Parent: "+this.parent);
        },0);

此 jquery 将执行一个回调,该回调在控制台中打印"单击"(未更改)单选按钮的名称和值。

$('input:radio').on('click', function(e) {
    console.log(e.currentTarget.name); //e.currenTarget.name points to the property name of the 'clicked' target.
    console.log(e.currentTarget.value); //e.currenTarget.value points to the property value of the 'clicked' target.
});

试试看:Fiddle

查找 change 事件的输入名称。

$('input:radio').on('change', function(e){
  var name = e.currentTarget.name,
  value = e.currentTarget.value;
            
  $('.name').text(name);
  $('.value').text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
     <input type="radio" name="input1" id="input1" value="option1"/>
     <input type="radio" name="input1" id="input1" value="option2"/>
</div>
<div class="btn-group btn-group-vertical" data-toggle="buttons">
     <input type="radio" name="input2" id="input2" value="option1"/>
     <input type="radio" name="input2" id="input2" value="option2"/>
</div>
<p>Name: <b class="name"></b></p>
<p>Value: <b class="value"></b></p>

编辑:对于其他任何想知道以下以下哪个问题到目前为止是"更多"正确的人,两者都是正确的,因为.change(function(e) {是.on('click',function(e){

是的,.change(function(e) {.on('click', function(e) {的快捷方式,但是当您使用部分视图时,例如在MVC中,页面中的链接或按钮.change(function(e) {会丢失hiperlink或无法正常工作,因此您必须使用.on('click', function(e) { hiperlink工作正常的地方。

最新更新