jQuery .prop('checked', true) 不起作用

aah*_*haa 4 html checkbox jquery input preventdefault

我有一组简单的复选框,可以检查多个选项,但我希望它表现得像一个单选按钮,总是有一个选项被选中。

正如您在我的代码中看到的那样,复选框将被选中,而不是取消选中。请让我知道我做错了什么。谢谢

$('input[type=checkbox]').on('click', function(event) {
		event.preventDefault();
		if($('input[type=checkbox]:checked').length === 1 && $(this).is(':checked')) {
				return false; 
                // there is only one checked AND the checked one is $this and we want to prevent it from uncheck
		} else {
			$(this).prop('checked', true);
			alert($(this).prop('checked')); // this return true
		} 

	});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked"/>
    <input type="checkbox"/>
        <input type="checkbox"/>
Run Code Online (Sandbox Code Playgroud)

Nev*_*ver 5

event.preventDefault()让你.prop不工作

当复选框被选中时,您还需要取消选中其他人。

$('input[type=checkbox]').on('click', function(event) {
  // Remove this line
  // event.preventDefault();
  
  if ($('input[type=checkbox]:checked').length === 1) {
    if ($(this).is(':checked')) {
      return false; // this is checked
    }
    return false; // and this is the only one check	
  } else {
    
    // Uncheck others
    $('input[type=checkbox]').prop('checked', false);
    
    $(this).prop('checked', true);
    alert($(this).prop('checked')); // this return true
  }


});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" />
Run Code Online (Sandbox Code Playgroud)