示例数据:
<input class="foo" special="yes" value="1" new="yes">
<input class="foo" special="no" value="2" new="yes">
<input class="foo" value="3" new="red">
<input class="foo" special="yes" value="4">
<input class="foo" value="5" new="yes">
现在的jQuery:
var the_inputs = $("input.foo");
...将为我提供所有输入的jquery对象。
我也可以:
var the_special_inputs = $("input.foo[special]");
...仅返回具有特殊属性的输入。
更进一步,我可以仅获得具有特殊属性的输入,其中它们还具有“yes”的新属性:
var the_special_inputs = $("input.foo[special][new='yes']");
但是,如果我只是想使用'the_inputs'并创建var
the_special_inputs
而又不做其他选择器该怎么办?用那里的话,如果我有存储的var:var the_inputs = $("input.foo");
...是否有一种方法可以在该存储的var上编写一个附加选择器,该选择器将为我提供与
$("input.foo[special]");
或上面类似的其他结果相同的结果,但仅使用以前存储的the_inputs
?我尝试过的一些方法不起作用:
$(the_inputs+"[special][new='yes']");
$("[special]",the_inputs);
是否可以?
最佳答案
var the_inputs = $("input.foo");
var the_special_inputs = the_inputs.filter("[special][new='yes']");
这将创建一个新集合,该集合将原始集合简化为与您通过的选择器匹配的集合,而无需执行其他DOM选择。
还有另一种方法called
.not()
保留那些与选择器不匹配的方法。