首页 > 解决方案 > 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"/>

标签: javascriptjqueryhtml

解决方案


不,你不能那样做,你应该先检测它是否被检查,我使用了一个变量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" />


推荐阅读