如何在变更事件中使用广播? [英] How to use radio on change event?
本文介绍了如何在变更事件中使用广播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个单选按钮 在更改事件上我想要更改按钮怎么可能? 我的代码
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>
推荐答案
您可以使用this
引用当前的input
元素.
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");
}
});
请注意,在不赞成使用if语句和:radio
选择器的情况下,您正在将值与allot
进行比较.
Note that you are comparing the value against allot
in both if statements and :radio
selector is deprecated.
如果您不使用jQuery,则可以使用document.querySelectorAll
和HTMLElement.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屋!
查看全文