如何在更改事件中使用广播? [英] How to use radio on change event?

查看:27
本文介绍了如何在更改事件中使用广播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单选按钮关于更改事件我想要更改按钮 这怎么可能?我的代码

I have two radio button on change event i want change button How it is possible? My Code

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer">Transfer

脚本

<script>
    $(document).ready(function () {
        $('input:radio[name=bedStatus]:checked').change(function () {
            if ($("input[name='bedStatus']:checked").val() == 'allot') {
                alert("Allot Thai Gayo Bhai");
            }
            if ($("input[name='bedStatus']:checked").val() == 'transfer') {
                alert("Transfer Thai Gayo");
            }
        });
    });
</script>

推荐答案

您可以使用引用当前 input 元素的 this.

You can use this which refers to the current input element.

$('input[type=radio][name=bedStatus]').change(function() {
    if (this.value == 'allot') {
        alert("Allot Thai Gayo Bhai");
    }
    else if (this.value == 'transfer') {
        alert("Transfer Thai Gayo");
    }
});

http://jsfiddle.net/4gZAT/

请注意,您正在将 if 语句和 :radio 选择器中的值与 allot 进行比较.

Note that you are comparing the value against allot in both if statements and :radio selector is deprecated.

如果您不使用 jQuery,您可以使用 document.querySelectorAllHTMLElement.addEventListener 方法:

In case that you are not using jQuery, you can use the document.querySelectorAll and HTMLElement.addEventListener methods:

var radios = document.querySelectorAll('input[type=radio][name="bedStatus"]');

function changeHandler(event) {
   if ( this.value === 'allot' ) {
     console.log('value', 'allot');
   } else if ( this.value === 'transfer' ) {
      console.log('value', 'transfer');
   }  
}

Array.prototype.forEach.call(radios, function(radio) {
   radio.addEventListener('change', changeHandler);
});

这篇关于如何在更改事件中使用广播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆