【问题标题】:if checkbox is checked, do this如果选中复选框,请执行此操作
【发布时间】:2011-05-13 17:08:53
【问题描述】:

当我选中一个复选框时,我希望它变成<p> #0099ff

当我取消选中复选框时,我希望它撤消它。

到目前为止我的代码:

$('#checkbox').click(function(){
    if ($('#checkbox').attr('checked')) {
        /* NOT SURE WHAT TO DO HERE */
    }
}) 

【问题讨论】:

  • "...未选中时,禁用相同的功能。" - 传递给.click() 的函数在点击事件上被调用。因此,我不明白您所说的“启用”和“禁用”是什么意思。如果选中该复选框,您可以调用函数a()。但是您必须编写反向函数以在复选框选中时调用。我很困惑。
  • 当然,您可以根据复选框状态将.bind().unbind() 事件发送到另一个 元素。这就是你所追求的吗?
  • 很抱歉发送了垃圾邮件,但我已经把我所说的内容写成了an example
  • 我知道这是一篇旧文章,但现在 jQuery 使用 prop() 来解决这个问题想要使用 attr() 的问题;当时还没有创建 prop() 方法。不过,关于this.checked 的答案可能仍然有用。

标签: jquery checkbox if-statement checked unchecked


【解决方案1】:

我会use.change()this.checked

$('#checkbox').change(function(){
    var c = this.checked ? '#f00' : '#09f';
    $('p').css('color', c);
});

--

关于使用this.checked
Andy E 写了一篇关于我们如何倾向于过度使用 jQuery 的精彩文章:Utilizing the awesome power of jQuery to access properties of an element。这篇文章专门讨论了.attr("id") 的使用,但在#checkbox 一个<input type="checkbox" /> 元素的情况下,$(...).attr('checked')(甚至$(...).is(':checked'))与@ 的问题是相同的987654333@.

【讨论】:

    【解决方案2】:

    试试这个。

    $('#checkbox').click(function(){
        if (this.checked) {
            $('p').css('color', '#0099ff')
        }
    }) 
    

    有时我们会过度使用 jquery。使用带有纯 javascript 的 jquery 可以实现很多事情。

    【讨论】:

      【解决方案3】:

      “this.checked”可能总是“开启”。因此,我建议:

      $('#checkbox').change(function() {
        if ($(this).is(':checked')) {
          console.log('Checked');
        } else {
          console.log('Unchecked');
        }
      });
      

      【讨论】:

      • 就我而言,我只是更改为$(':checkbox') 以使其正常工作;)
      【解决方案4】:

      如果你定义一个不同颜色的类会更好,然后你切换类

      $('#checkbox').click(function(){
          var chk = $(this);
          $('p').toggleClass('selected', chk.attr('checked'));
      }) 
      

      这样你的代码会更干净,因为你不必指定所有的 css 属性(假设你想添加边框、文本样式或其他...),但你只需切换一个类

      【讨论】:

      • +1 用于通用解决方案。没有理由做$('#checkbox').attr('checked'),但是,如果我们知道#checkbox 一个复选框(如果不是,ID 相当误导)。 this.checked 可以。
      • @jensgram @fcalderan +1 感谢您的提示!我从未见过带开关的toggleClass。我正在删除我的帖子,因为它没用。很抱歉这么挑剔,但我认为如果没有两次选择“#checkbox”,这个答案将是 100% 完美:也许使用 $(this) 代替?还是 jensgram 的解决方案?
      • @attack 当然你可以在使用之前缓存你的元素(现在看代码)。 this.checked 甚至比 $(..).attr('checked') 还要快
      【解决方案5】:

      我发现了一个疯狂的解决方案来处理复选框未选中或选中的问题 这是我的算法... 创建一个全局变量让我们说 var check_holder

      check_holder有3个状态

      1. 未定义状态
      2. 0 状态
      3. 1 个州

      如果复选框被点击,

      $(document).on("click","#check",function(){
          if(typeof(check_holder)=="undefined"){
                //this means that it is the first time and the check is going to be checked
                //do something
                check_holder=1; //indicates that the is checked,it is in checked state
          }
          else if(check_holder==1){
                //do something when the check is going to be unchecked
                check_holder=0; //it means that it is not checked,it is in unchecked state
          }
           else if(check_holder==0){
                  //do something when the check is going to be checked
                  check_holder=1;//indicates that it is in a checked state
           }
      });
      

      上面的代码可以在很多情况下用来判断一个复选框是否被选中。其背后的概念是将复选框状态保存在一个变量中,即当它打开、关闭时。 我希望逻辑可以用来解决你的问题。

      【讨论】:

      • 解决方案确实很疯狂,但不是很好。是的,全局变量可以帮助您今天解决问题,但它们几乎肯定会在明天成为您的问题。尽量避免它们,这是 99% 的时间。它们使您无法在不担心全局状态的情况下推理您的代码。一个全局变量可能看起来很无辜,但很快它就会变成几十甚至几百。去过那里,看到了,并不漂亮。
      【解决方案6】:

      检查此代码:

      <!-- script to check whether checkbox checked or not using prop function -->
      <script>
      $('#change_password').click(function(){
          if($(this).prop("checked") == true){ //can also use $(this).prop("checked") which will return a boolean.
              alert("checked");
          }
          else if($(this).prop("checked") == false){
              alert("Checkbox is unchecked.");
          }
      });
      </script>
      

      【讨论】:

        【解决方案7】:
        $('#checkbox').change(function(){
           (this.checked)?$('p').css('color','#0099ff'):$('p').css('color','another_color');
        });
        

        【讨论】:

          【解决方案8】:

          也许您可以使用此代码在复选框被选中或取消选中时执行操作。

          $('#chk').on('click',function(){
              if(this.checked==true){
                alert('yes');
              }else{
                alert('no');
              }
          });
          

          【讨论】:

            【解决方案9】:

            我愿意:

            $('#checkbox').on("change", function (e){ 
            
                if(this.checked){
            
                  // Do one thing 
            
                }
            
                else{
            
                 // Do some other thing
            
                }
            
            });
            

            见:https://www.w3schools.com/jsref/prop_checkbox_checked.asp

            【讨论】:

              【解决方案10】:

              最佳实施

              $('#checkbox').on('change', function(){
                  $('p').css('color', this.checked ? '#09f' : '');
              });
              

              演示

              $('#checkbox').on('change', function(){
                  $('p').css('color', this.checked ? '#09f' : '');
              });
              <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
              <input id="checkbox" type="checkbox" /> 
              <p>
                  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                  eiusmod tempor incididunt ut labore et dolore magna aliqua.
              </p>
              <p>
                  Ut enim ad minim veniam, quis nostrud exercitation ullamco
                  laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
                  dolor in reprehenderit in voluptate velit esse cillum dolore eu
                  fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                  proident, sunt in culpa qui officia deserunt mollit anim id est
                  laborum.
              </p>

              【讨论】:

                【解决方案11】:

                为什么不使用内置事件?

                $('#checkbox').click(function(e){
                    if(e.target.checked) {
                     // code to run if checked
                        console.log('Checked');
                
                     } else {
                
                     //code to run if unchecked
                        console.log('Unchecked');
                     }
                });
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-02-02
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-02-11
                  • 2018-07-29
                  相关资源
                  最近更新 更多