【问题标题】:jquery How to access only checked checkbox?jquery如何访问仅选中的复选框?
【发布时间】:2012-05-26 17:50:18
【问题描述】:

我有一个包含 7 checkboxes 的 div,我编写了以下代码用于访问 only the checked checkboxarray icons

var icons = $("div").find("input[type=checkbox]").each(function () { 
if($(this).attr("checked") == "checked") return this; });

alert(icons.length);

但它总是提醒 7 。有人可以告诉我问题吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:
var icons = $("div").find("input[type=checkbox]:checked");

【讨论】:

  • @user1400722 很高兴我能帮上忙
【解决方案2】:

最简单的方法是为目标输入分配一个类并使用checked selector,请参见下面的示例:

var icons = $('.box:checked');

【讨论】:

  • 如果我们能像@mgraph 和 ThulasiRam 回答的那样,上课需要什么
  • @user1400722 $("div") 将找到您页面上的每个 div
【解决方案3】:

演示 http://jsfiddle.net/KzMqB/

您可能只需要使用:checked 进行检查一次,它就会为您提供所需的内容。

好读:http://api.jquery.com/checked-selector/

希望这会有所帮助!

代码

var icons = $("div").find("input[type=checkbox]:checked").each(function() {
           alert("ID of checked checkbox = " + $(this).attr("id"));
});

【讨论】:

    【解决方案4】:

    你可以使用$.map

    $(document).ready(function() {
        var checks = $.map($("div").find('input[type="checkbox"]:checked'),function(arr){
            return arr;
        })
        console.log(checks.length);
    })
    

    或者你的方法,

    $(document).ready(function() {
        var checks = $.each($("div").find('input[type="checkbox"]:checked'),function(){
            return this;
        })
        console.log(checks.length);
    })
    

    【讨论】:

    • 好吧,checks 会有正确的元素,但不是因为$.each。回调的返回值决定$.each 是否应该继续迭代元素。返回值是您传递给它的第一个参数。所以本质上,您的代码与var checks = $("div").find('input[type="checkbox"]:checked'); 完全相同,只是更加复杂。绝对没有必要使用每个。查看文档:api.jquery.com/jQuery.each.
    • 是的。我现在已经看到了,没有必要重复。这个问题在我脑海中,我只是试图以它的风格解决问题。非常感谢 !我很感激。
    【解决方案5】:
    var icons= $("div").find("input:checked").length;
    alert(icons);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多