【问题标题】:Check if 'this' checkbox is checked检查是否选中了“this”复选框
【发布时间】:2012-02-09 16:00:58
【问题描述】:

如何判断是否使用 this 命令选中了“this”复选框?

我有以下内容,但不确定如何实现(因此它只检查选中的单个复选框,而不是页面上的所有复选框

if ($('input[type="checkbox"]').is(':checked')

【问题讨论】:

    标签: jquery checkbox


    【解决方案1】:

    大概你的意思是 this 在事件处理程序的上下文中......在这种情况下,只需测试 checked 属性:

    $('input[type="checkbox"]').click(function() {
        if (this.checked) {
            // checkbox clicked is now checked
        }
    });
    

    请注意,您可以使用以下方法执行相同操作:

    • $(this).is(':checked')
    • $(this).prop('checked')

    但是,this.checked 避免创建新的 jQuery 对象,因此效率更高(并且编码速度更快)。 is 是最慢的:它花费的时间是 prop 的两倍,大约是简单属性查找的 100 倍。

    jsPerf comparison between this techniques

    【讨论】:

      【解决方案2】:

      查看prop()http://api.jquery.com/prop/

      文档提供了多种更好的方法来检查“已选中”复选框。

      elem.checked                      |  true (Boolean) Will change with checkbox state
      $(elem).prop("checked")           |  true (Boolean) Will change with checkbox state
      elem.getAttribute("checked")      |  "checked" (String) Initial state of the checkbox; does not change
      $(elem).attr("checked")(1.6)      |  "checked" (String) Initial state of the checkbox; does not change
      $(elem).attr("checked")(1.6.1+)   |  "checked" (String) Will change with checkbox state
      $(elem).attr("checked")(pre-1.6)  |  true (Boolean) Changed with checkbox state
      

      【讨论】:

        【解决方案3】:

        你的意思是这样的吗(0是索引):

        if ($(':checkbox').get(0).is(':checked'))
        

        或者像这样:

        if ($(this).is(':checked'))
        

        【讨论】:

          【解决方案4】:

          我使用以下:

          $(this).find('input[type="checkbox"]:checked')
          

          这个例子返回所有被选中的复选框

          【讨论】:

            【解决方案5】:

            试试下面的,你知道id的地方

            $('#edit-checkbox-id').is(':checked'); 
            

            或者如果您已经使用此关键字引用该项目

            $(this).is(':checked');
            

            【讨论】:

              【解决方案6】:

              您需要使用 ID 选择器。 input[type="checkbox"] 选择器将返回'所有复选框。

              if ($('#Checkbox1').is(':checked'))
              

              其中 Checkbox1 是复选框的 ID

              【讨论】:

                【解决方案7】:

                这个怎么样?

                if($(this).is(':checked'))
                

                【讨论】:

                • 这行得通,但这不是好的做法。请参阅我的答案,了解为什么这非常低效。
                猜你喜欢
                • 1970-01-01
                • 2013-10-28
                • 1970-01-01
                • 2018-03-27
                • 2012-07-13
                • 2016-04-22
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多