我想在单击时切换一个单选按钮,但它总是返回true,而不是未选中。当无线电被选中时,我想调用一个函数,在未被选中的情况下运行另一个函数,我如何做到这一点?
$('input[type="radio"]').click(function() {
console.log($(this).is(':checked'))
if ($(this).is(':checked')) {
$(this).attr('checked', false)
} else {
$(this).attr('checked', true)
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="ch"/>
<input type="radio" name="ch"/>
发布于 2020-02-04 09:05:19
您可以使用.prop()与isChecked变量相结合来实现它。
var isChecked = false;
$('input[type="radio"]').click(function() {
$(this).prop('checked', !isChecked);
isChecked = !isChecked;
if(isChecked) f1();
else f2();
});
var f1 = function(){
console.log("F1");
};
var f2 = function(){
console.log("F2");
};<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" />
更新的
您还可以使用以下两个单选按钮
$('input[type="radio"]').click(function() {
var value = $(this).filter(":checked").val();
if(value === 'f1')
f1();
else
f2();
});
var f1 = function(){
console.log("F1");
};
var f2 = function(){
console.log("F2");
};<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="my_radio" value="f1" /> <label>F1</label>
<input type="radio" name="my_radio" value="f2" /> <label>F2</label>
https://stackoverflow.com/questions/60053831
复制相似问题