我知道如何获取具有特定属性的元素:
$("#para [attr_all]")
Run Code Online (Sandbox Code Playgroud)
但是如何才能获得没有特定属性的元素?我试试
$("#para :not([attr_all])")
Run Code Online (Sandbox Code Playgroud)
但它不起作用.这样做的正确方法是什么?
让我举个例子:
<div id="para">
<input name="fname" optional="1">
<input name="lname">
<input name="email">
</div>
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$("#para [optional]") // give me the fname element
$("#para :not([optional])") //give me the fname, lname, email (fname should not appear here)
Run Code Online (Sandbox Code Playgroud)
Fra*_*osa 115
如果您的代码示例是您正在使用的确切代码,我认为问题是错误的空间.
$("#para :not([attr_all])")
Run Code Online (Sandbox Code Playgroud)
应该
$("#para:not([attr_all])")
Run Code Online (Sandbox Code Playgroud)
如果你在那里留下一个空间,它选择的后代的#para
.
Pim*_*ger 20
我想到的第一件事(可能是次优的):
$('p').filter(function(){
return !$(this).attr('attr_all');
});
Run Code Online (Sandbox Code Playgroud)
但是p:not([attr_all])
应该可以工作,所以我认为你的代码中正在发生其他事情.
更快的方法是首先获取ID为para的所有元素(如果有多个,则为无效HTML,请考虑使用类)并使用过滤器(或根据HTML的构造方式查找)方法只获取没有属性的元素,如下所示:
$('#para').filter(':not([attr_all])');
Run Code Online (Sandbox Code Playgroud)
这样做你让jQuery做的工作少得多,因为你只是循环一小部分元素来获得那些没有属性的元素.例如$("#para :not([attr_all])")
,使用单个选择器语句执行此操作将导致jQuery获取没有该属性的所有元素,然后将其过滤为ID为para的元素.
归档时间: |
|
查看次数: |
29457 次 |
最近记录: |