2013-02-18 63 views
0

如何选择名为id =“Paragraph1”的段落中的每个子复选框,并取消选中它,如果它的选中,然后禁用它在jQuery中。jQuery为每个孩子复选框在一个段落编号

实施例:

<input type="checkbox" id="chkMain"><br /> 
<p id="Paragraph1"> 
    <input type="checkbox" id"chk1"><br /> 
    <input type="checkbox" id"chk2"><br /> 
    <input type="checkbox" id"chk3"><br /> 
    <input type="checkbox" id"chk4"><br /> 
</p> 

jQuery的选择:

$("#chkMain:not(:checked)").change(function() { 
    $("#Paragraph1").children("input[type='checkbox' :checked]").each(function() { 
     $(this).removeAttr("checked").attr("disabled",disabled");  
    }); 
}); 

该代码是不正确的工作二/三其仅工作一半的时间由于某种原因在IE8。也使用查找不工作的权利或者B/C段落不是一个好父母。

回答

1

input[type='checkbox' :checked]是不正确的选择器。

它应该是:

input[type='checkbox']:checked

而且我认为你可以简化像代码:

$('#Paragraph1 input[type="checkbox"]:checked') // select all checked input 
        .removeAttr('checked')  // remove checked attribute 
        .prop('disabled', true);  // make em disabled 
1

替换这一切:

$("#Paragraph1").children("input[type='checkbox' :checked]").each(function() { 
    $(this).removeAttr("checked").attr("disabled",disabled");  
    }); 

有了这个:

$("#Paragraph1 input[type='checkbox']:checked") 
    .prop('checked', false) 
    .prop('disabled', true); 
  • ,当你想要做的东西是不可用jQuery的API的每一个元素上设置的,像alert或发送AJAX请求您应该使用each

  • 当你可以使用prop时,不要乱用属性。

  • CSS选择器中的空间意味着“children of”,因此请删除:checked的空间并在Paragraph1和输入之间添加一个空格。直接孩子,你可以使用parent > children

喜欢这一点:

$("#Paragraph1 > input[type='checkbox']:checked") 
    .prop('checked', false) 
    .prop('disabled', true); 
+0

这是否工作jQuery的1.7.2.js?无法得到这个工作。另外我没有看到.prop作为一个实际功能。 – RetroCoder 2013-02-18 21:19:13

+0

@RetroCoder,是的,它的作品。至于'道具',你的坏... – gdoron 2013-02-19 08:42:22

1

有在你的代码的几个语法错误,你可以使用prop方法:

$("#chkMain").change(function() { 
    $("#Paragraph1 input[type='checkbox']") 
       .prop('checked', this.checked) 
       .prop('disabled', !this.checked) 
}); 
+0

无法得到这个工作。 – RetroCoder 2013-02-18 21:44:14

相关问题