在jQuery每个循环中检查是否检查复选框的问题

时间:2011-03-23 17:52:05

标签: jquery checkbox each

我想知道这里是否有人可以帮助解决这个问题我如果选中复选框则指定var值为1,如果没有在每个循环中检查jQuery,则指定0。

我有一个html列表,如下所示:

<ul id="role-list">

<li id="role_1">
<p>Read<input type="checkbox" class="read"> Write<input type="checkbox" class="write"></p>
</li>

<li id="role_4">
<p>Read<input type="checkbox" class="read"> Write<input type="checkbox" class="write"></p>
</li>

<li id="role_5">
<p>Read<input type="checkbox" class="read"> Write<input type="checkbox" class="write"></p>
</li>

</ul>

我正在尝试使用以下代码使用jQuery创建一个多维数组:

var roles = {};
   $('#role-list li').each(function() {

   var role_id = jQuery(this).attr('id').replace('role_', '');

   roles[role_id] = {};
   $('input[type=checkbox]').each(function () {

    roles[role_id][jQuery(this).attr('class')] = $(this).checked ? 1 : 0;

});

});
    alert(JSON.stringify(roles));

这是我得到的输出,无论是否选中任何复选框,都是相同的:

{"1":{"read":0,"write":0},"4":{"read":0,"write":0},"5":{"read":0,"write":0}}

我得到的问题是代码:

$(this).checked ? 1 : 0;

似乎无法正常工作。我尝试了多种变体尝试在发布之前使其工作,但我仍然没有运气。

任何帮助都将不胜感激。

由于

.............

我最终决定删除复选框的每个循环,并使用以下正常工作的代码:

var roles = {};
   $('#role-list li').each(function() {

   var role_id = jQuery(this).attr('id').replace('role_', '');

   roles[role_id] = {};

   roles[role_id]['read'] = jQuery(this).find('.read').is(':checked') ? 1 : 0;

   roles[role_id]['write'] = jQuery(this).find('.write').is(':checked') ? 1 : 0

});

1 个答案:

答案 0 :(得分:1)

你想要

$(this).is(':checked')
-or-
$(this).attr('checked')
-or-
this.checked

或将您的查询更改为:

$('input[type=checkbox]:checked')

在这种情况下你根本不需要三元组,这可能是更好的选择,因为你没有用零填充角色(你可能想要?)

$(this).checked不存在,因为$(this)是一个jquery对象,.checked是单个元素的属性。