简体   繁体   English

如何选中/取消选中键盘上的复选框

[英]how to check/uncheck a checkbox on keyup

I have been trying to make a script that checks and unchecks a checkbox when I press the 'c' key but it doesn't work. 我一直在尝试制作一个脚本,当我按下'c'键时,该脚本可以检查和取消选中复选框,但是它不起作用。

$(document).keyup(function(e){
  if(e.which == 67){
    if($('#main').css('opacity') == 0) {
    if ($('#cHideChat').attr('checked')) {
    $('#cHideChat').prop('checked', false);
    }
    else {
    $('#cHideChat').prop('checked', true);
      }
    }
  }
});

You can do it like this 你可以这样

 $(document).on('keyup', function(e) { var checkBox = $('#cHideChat') if ($('#main').css('opacity') == 0) { if (e.which == 67) checkBox.prop("checked", !checkBox.prop("checked")); } }); 
 #main { opacity: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="" id="cHideChat"> <div id="main"></div> 

You need to check for prop like so: 您需要像这样检查prop

$(document).keyup(function(e){
  if(e.which == 67){
    if($('#main').css('opacity') == 0) {
    if ($('#cHideChat').prop('checked')) {  // check for prop, not attr
    $('#cHideChat').prop('checked', false);
    }
    else {
    $('#cHideChat').prop('checked', true);
      }
    }
  }
});

I think the issue isn't related to the jQuery. 我认为这个问题与jQuery无关。 Although Nenad and Sandeep provided better way to achieve what you want, the jQuery code should run fine. 尽管Nenad和Sandeep提供了更好的方法来实现您想要的功能,但是jQuery代码应该运行良好。 However I see two other issues: 但是我看到另外两个问题:

First of all, key code 67 corresponds to the upper 'C', thus your code does not respond to lower 'c' presses. 首先,键代码67对应于较高的“ C”,因此您的代码不响应较低的“ c”按下。 The key code for lower 'c' is 99. Second, there is no attribute "checked". 较低的'c'的键代码为99。第二,没有“选中”属性。 It's a property and you should query it through .prop("checked") instead .attr("checked") . 这是一个属性,您应该通过.prop("checked")而不是.attr("checked") The latter returns undefined which corresponds to false and your condition is never met. 后者返回undefined ,它对应于false并且永远不会满足您的条件。 So just edit your code as Nenad Vracar suggested, but make sure to check for key code 99 like so: 因此,只需按照Nenad Vracar的建议编辑您的代码,但请确保像这样检查关键代码99:

if (e.which == 67 || e.which == 99) {
    checkBox.prop("checked", !checkBox.prop("checked"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM