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

VB_*_*VB_ 6 html javascript css jquery

如何让动态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>
Run Code Online (Sandbox Code Playgroud)

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

编辑2:删除了ID

eca*_*izo 8

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

$('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.
});
Run Code Online (Sandbox Code Playgroud)

试试吧: 小提琴


Sha*_*ggy 6

要提供纯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);
Run Code Online (Sandbox Code Playgroud)

另外,正如您提到的,组的数量是动态的,您可能需要一个活动节点列表,该列表需要一些额外的代码来检查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);
Run Code Online (Sandbox Code Playgroud)


Der*_*k S 5

找到change事件输入的名称.

$('input:radio').on('change', function(e){
  var name = e.currentTarget.name,
  value = e.currentTarget.value;
            
  $('.name').text(name);
  $('.value').text(value);
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)