我在想这里是否有人可以帮助解决这个问题我在分配一个var值为1的复选框,如果没有在每个jQuery的循环中检查0。查询是否在每个循环中检查复选框是否在jQuery中检查
我有一个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}}
问题我是GE特丁是代码:
$(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
});
为什么使用对象字面值var'roles = {}'而不是数组'var roles = []'? – 2011-03-23 18:00:28
你得到了什么输出? – Belinda 2011-03-23 18:02:37
@Belinda - 我已经更新了问题以显示我得到的输出。谢谢 – 2011-03-23 18:17:21