【问题标题】:jQuery checkbox checked state changed eventjQuery 复选框选中状态更改事件
【发布时间】:2012-01-15 10:20:15
【问题描述】:

我希望在选中/取消选中复选框时触发客户端的事件:

$('.checkbox').click(function() {
  if ($(this).is(':checked')) {
    // Do stuff
  }
});

基本上我希望它发生在页面上的每个复选框上。这种点击触发并检查状态的方法好吗?

我在想一定有一个更干净的 jQuery 方式。有人知道解决办法吗?

【问题讨论】:

  • 有没有必要再问这个问题,在stackoverflow中存在一个投票最高的相同问题......stackoverflow.com/questions/901712/…
  • @Arif 我不认为它们是重复的,因为链接的问题是关于获取复选框的状态,而这个问题是关于选中的事件。
  • 我总是要搜索这个checked属性,有很多方法可以实现这个as written here

标签: javascript jquery event-handling


【解决方案1】:

也可以如下实现。当复选框被触发时,div 或带有#checkbox id 的控件被隐藏或以其他方式显示。

 <script>
      $('#checkbox').on('click',function(){
          if(this.checked){
              $('#checkbox').hide();
           }else{
              $('#checkbox').show();
           }
      });
 </script>

【讨论】:

    【解决方案2】:

    试试这个“html-approach”acceptable for small JS projects

    function msg(animal,is) {
      console.log(animal, is.checked);   // Do stuff
    }
    <input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
    <input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
    ...

    【讨论】:

      【解决方案3】:

      很简单,我就是这样用的:

      JQuery:

      $(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
          var checkbox = $(this), // Selected or current checkbox
              value = checkbox.val(); // Value of checkbox
      
          if (checkbox.is(':checked'))
          {
              console.log('checked');
          }else
          {
              console.log('not checked');
          }
      });
      

      问候!

      【讨论】:

        【解决方案4】:

        为了方便以后有困难的人参考,如果您动态添加复选框,上面正确的accepted answer 将不起作用。您需要利用event delegation,它允许父节点从特定后代捕获冒泡事件并发出回调。

        // $(<parent>).on('<event>', '<child>', callback);
        $(document).on('change', '.checkbox', function() {
            if(this.checked) {
              // checkbox is checked
            }
        });
        

        请注意,几乎总是不需要使用document 作为父选择器。而是选择更具体的父节点,以防止将事件传播到太多级别。

        下面的例子展示了动态添加的 dom 节点的事件如何不触发之前定义的监听器。

        $postList = $('#post-list');
        
        $postList.find('h1').on('click', onH1Clicked);
        
        function onH1Clicked() {
          alert($(this).text());
        }
        
        // simulate added content
        var title = 2;
        
        function generateRandomArticle(title) {
          $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
        }
        
        setTimeout(generateRandomArticle.bind(null, ++title), 1000);
        setTimeout(generateRandomArticle.bind(null, ++title), 5000);
        setTimeout(generateRandomArticle.bind(null, ++title), 10000);
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <section id="post-list" class="list post-list">
          <article class="post">
            <h1>Title 1</h1>
          </article>
          <article class="post">
            <h1>Title 2</h1>
          </article>
        </section>

        虽然此示例显示了使用事件委托来捕获特定节点(本例中为h1)的事件,并为此类事件发出回调。

        $postList = $('#post-list');
        
        $postList.on('click', 'h1', onH1Clicked);
        
        function onH1Clicked() {
          alert($(this).text());
        }
        
        // simulate added content
        var title = 2;
        
        function generateRandomArticle(title) {
          $postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
        }
        
        setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <section id="post-list" class="list post-list">
          <article class="post">
            <h1>Title 1</h1>
          </article>
          <article class="post">
            <h1>Title 2</h1>
          </article>
        </section>

        【讨论】:

        • 太棒了。我刚刚在这里了解了更多基础知识。
        • 这解释了“为什么”我的点击事件不起作用 - 谢谢!!
        • 注意:对于父级(在上面的示例中:#post-list),您必须使用不是动态创建的文档元素。在我的例子中,包含部分视图的 div。
        【解决方案5】:

        这是找到复选框是否选中的解决方案。 使用#prop() 函数//

        $("#c_checkbox").on('change', function () {
                            if ($(this).prop('checked')) {
                                // do stuff//
                            }
                        });
        

        【讨论】:

          【解决方案6】:

          试试这个 jQuery 验证

          $(document).ready(function() {
            $('#myform').validate({ // initialize the plugin
              rules: {
                agree: {
                  required: true
                }
          
              },
              submitHandler: function(form) {
                alert('valid form submitted');
                return false;
              }
            });
          
          });
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
          
          <form id="myform" action="" method="post">
            <div class="buttons">
              <div class="pull-right">
                <input type="checkbox" name="agree" /><br/>
                <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>
              </div>
            </div>
            <button type="submit">Agree</button>
          </form>

          【讨论】:

            【解决方案7】:

            基于事件(点击事件)采取的行动。

            $('#my_checkbox').on('click',function(){
               $('#my_div').hide();
               if(this.checked){
                 $('#my_div').show();
               }
            });
            

            没有基于当前状态采取行动的事件。

            $('#my_div').hide();
            if($('#my_checkbox').is(':checked')){
              $('#my_div').show();
            }
            

            【讨论】:

            • on 'click' 事件在这种情况下不起作用。关于“改变”的作品。
            【解决方案8】:
            $(document).ready(function () {
                $(document).on('change', 'input[Id="chkproperty"]', function (e) {
                    alert($(this).val());
                });
            });
            

            【讨论】:

              【解决方案9】:

              也许这可能是您的替代方案。

              <input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
              

              【讨论】:

                【解决方案10】:

                只是另一种解决方案

                $('.checkbox_class').on('change', function(){ // on change of state
                   if(this.checked) // if changed state is "CHECKED"
                    {
                        // do the magic here
                    }
                })
                

                【讨论】:

                • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
                【解决方案11】:

                如果您的意图是仅在选中的复选框上附加事件(因此当它们未选中并稍后再次选中时它会触发)那么这就是您想要的。

                $(function() {
                    $("input[type='checkbox']:checked").change(function() {
                
                    })
                })
                

                如果您打算将事件附加到所有复选框(选中和未选中)

                $(function() {
                    $("input[type='checkbox']").change(function() {
                
                    })
                })
                

                如果您希望它仅在它们被检查(未检查)时触发,那么@James Allardice 在上面回答。

                顺便说一句,input[type='checkbox']:checked 是 CSS 选择器。

                【讨论】:

                • 如果您只想找到未选中的复选框怎么办?我对所有检查都有这个 $("#tableUSNW tbody tr td[id=td1] :checkbox:checked");但我不知道如何找到所有未选中的。
                • @FrenkyB 尝试关注:$("input[type='checkbox']:not(:checked)")
                【解决方案12】:

                绑定到change 事件而不是click。但是,您可能仍需要检查复选框是否被选中:

                $(".checkbox").change(function() {
                    if(this.checked) {
                        //Do stuff
                    }
                });
                

                click 事件相比,绑定change 事件的主要好处是,并非所有对复选框的点击都会导致它改变状态。如果您只想捕获导致复选框更改状态的事件,则需要恰当命名的 change 事件。 在 cmets 中编辑

                另外请注意,我使用this.checked 而不是将元素包装在 jQuery 对象中并使用 jQuery 方法,仅仅是因为直接访问 DOM 元素的属性更短、更快。

                编辑(参见 cmets)

                要获得所有复选框,您有几个选项。您可以使用:checkbox 伪选择器:

                $(":checkbox")
                

                或者您可以使用attribute equals 选择器:

                $("input[type='checkbox']")
                

                【讨论】:

                • 其实我已经得到它寻找类的复选框。有没有更好的方法来获取所有复选框而不考虑类别?
                • @AnonyMouse - 查看我的编辑。有几种方法可以做到这一点。
                • @Vigrond - 实际上,单击标签确实会触发关联控件上的单击事件:jsfiddle.net/ZFG84
                • 这比$(this).is(':checked')干净多了。我认为如果你想检测来自键盘的变化(制表符、敲击空格),你必须使用 change 事件,但令人惊讶的是,click 也检测到不是来自鼠标点击的变化,不确定它是否是jQuery 的东西,jsfiddle.net/mendesjuan/E39sz
                • 请注意: 将任何事件clickchange 或任何事件绑定到页面上的所有复选框都可能导致性能问题(取决于复选框的数量)。尝试绑定到父元素或文档并捕获冒泡事件,即$('form').on('change', ':checkbox', function(){ //stuff });
                猜你喜欢
                • 2021-12-19
                • 1970-01-01
                • 2012-08-11
                • 1970-01-01
                • 1970-01-01
                • 2023-03-05
                • 2015-04-10
                • 2013-08-08
                • 1970-01-01
                相关资源
                最近更新 更多