如何使用jQuery选择所有空标签。
我想要选择:
<p></p>
<p style="display: block"></p>
<p> </p>
<p> </p>
<p> </p>
而不是
<p>0</p>
<p>Test</p>
我尝试使用
:empty
,但它与我的选项不兼容。非常感谢您的任何帮助。jQuery.filter()
来完成此操作。var empty_p = $('p').filter(function(){
return !$.trim($(this).text());
}).get();
IE
兼容。 - Nauphal$(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, "");
}
}
的中文翻译为:{{链接1:JS FIDDLE}}
。
。 - Fabrício Matté您可以使用jQuery的filter和trim方法来实现这一点。
这里有一个可工作的示例:http://jsfiddle.net/snqSw/
$("p").filter(function(){
$(this).text($.trim($(this).text())==""?"Works":$(this).text());
});
还有一种方法可以做到这一点,使用正则表达式而不是 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>
根据你想要对段落进行的操作,这可能或可能不是你想要的。如果不是,你需要更复杂的东西;具体细节将取决于你认为什么样的段落是“空白”的。
:empty
的例子吗? - macwier