如何使用jQuery选择所有空标记。
我想选择
<p></p>
<p style="display: block"></p>
<p> </p>
<p> </p>
<p> </p>
而不是
<p>0</p>
<p>Test</p>
我尝试使用:empty
,但它无法使用我的选项。非常感谢任何帮助。
答案 0 :(得分:7)
您可以使用jQuery.filter()
。
var empty_p = $('p').filter(function(){
return !$.trim($(this).text());
}).get();
答案 1 :(得分:2)
$('p').filter(function () {
return !$(this).text().trim();
});
答案 2 :(得分:1)
$(document).ready(function(){
$("p").each(function(index){
var html = $(this).html();
html = filter(html, " ");
html = filter(html, " ");
if ($(this).html() == ""){
//YOUR CODE
}
});
});
function filter(string, char){
while(string.indexOf(char) > 0){
string.replace(char, "");
}
}
答案 3 :(得分:0)
您可以使用jquery filter和trim方法执行此操作 这是一个有效的例子:http://jsfiddle.net/snqSw/
$("p").filter(function(){
$(this).text($.trim($(this).text())==""?"Works":$(this).text());
});
答案 4 :(得分:-1)
另一种方法是使用regexp而不是trim()
:
$('p').filter(function () {
return !/\S/.test( $(this).text() );
})
(JSFiddle)
请注意,此(以及基于$(this).text()
的所有其他解决方案)也会匹配,例如:这一段:
<p><a href="http://example.com"> </a></p>
甚至:
<p><img src="http://example.com/image.gif"></p>
根据您对段落的处理方式,这可能是您想要的,也可能不是。如果不是,你将需要一些更复杂的东西;细节将取决于你想要考虑一个“空”段落的确切内容。