Javascript 在jQuery中链接不同类型的选择器
我是jQuery的新手,在弄清楚如何链接选择器时遇到了困难。目标是选择具有“.restricted”类的复选框。以下是我的JS控制台的输出:Javascript 在jQuery中链接不同类型的选择器,javascript,jquery,html,Javascript,Jquery,Html,我是jQuery的新手,在弄清楚如何链接选择器时遇到了困难。目标是选择具有“.restricted”类的复选框。以下是我的JS控制台的输出: > $("#capability_panel input[type='checkbox']") [ <input type="checkbox" id="jbp_product_workshops" value="option1"> , <input type="checkbox" id="jbp_elevate_cr
> $("#capability_panel input[type='checkbox']")
[
<input type="checkbox" id="jbp_product_workshops" value="option1">
,
<input type="checkbox" id="jbp_elevate_creators" value="option2" class="restricted">
,
<input type="checkbox" id="jbp_trainings" value="option3">
,
<input type="checkbox" id="jbp_resources_ask" value="option4" class="restricted">
,
<input type="checkbox" id="jbp_talent_exchange" value="option5" class="restricted">
]
> $("#capability_panel input[type='checkbox'] .restricted")
[]
> $("#capability_panel input[type='checkbox']").find(".restricted")
[]
我一定是在做傻事,对吧
$("input[type='checkbox'].restricted")
将所有复选框与类限制匹配
当您给$input[type='checkbox'].restricted这样的空格时,它将查找类受限的子元素
同样,$capability_面板输入[type='checkbox']。find.restricted将在父级中查找具有受限类的元素。这是不可能的,因为JQuery中的父项是一个复选框,选择器的工作方式与CSS类似 如果希望复选框包含受限类,则必须编写: $capability_面板输入[type='checkbox']。受限
$capability_面板输入[type='checkbox'].restricted和$capability_面板输入[type='checkbox'].find.restricted将首先选择复选框输入,并尝试在其中查找受限类的元素 jQuery正在使用CSS选择器和其他工具来选择元素 也就是说,您可以使用该选择器实现您想要的:
$("#capability_panel input[type='checkbox'].restricted");
如果要使用函数获取每个匹配复选框,可以使用:
使用过滤器或选择器的主要区别在于您想要实现什么。例如,如果要选中除.restricted复选框之外的所有复选框,可以使用:
$("#capability_panel input[type='checkbox']").prop('checked', true).filter('.restricted').prop('checked', false);
当然,这是一个基本的例子,有最佳的方法可以做到这一点。$input[type='checkbox']
$("#capability_panel input[type='checkbox']").prop('checked', true).filter('.restricted').prop('checked', false);