javascript - jQuery 切换单选按钮
问题描述
我想在点击时切换一个单选按钮,但它总是返回 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"/>
解决方案
不,你不能那样做,你应该先检测它是否被检查,我使用了一个变量checked
function f1() {
console.log('run 1st func!')
}
function f2() {
console.log('run 2nd func!')
}
let checked = true
$('input:radio').click(function() {
let bu = $(this);
checked = !checked
checked ? bu.prop('checked', !this.checked) + f1() :
bu.prop('checked', this.checked) + f2()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" />
推荐阅读
- ejabberd - ejabberd: AccessRules: 账户无权执行该操作
- java - 在 Eclipse 中运行 TestNG 单元测试会忽略最新的更改
- azure-machine-learning-service - 如果 Azure 机器学习中的部署变得“不健康”,如何生成警报?
- c++ - 如何将 VS、C++、OpenGL 应用程序部署到第二台计算机?
- c# - 在 Unity 3D 中保留我的十进制计算
- r - R slidy_presentation 中的两列幻灯片
- nix - 关于 Nix 包管理的 Nix 表达式是什么?
- python - 如何检查for循环是否在中间值
- ruby-on-rails - 当我想重新注册表单时收到以下错误:NoMethodError (undefined method `permit' for "create":String)
- javascript - jquery touchswipe 插件在 iOS 上无法正常工作