我正在尝试从 DOM 树中删除所有空标签。空意味着完全空(如 <a></a>
)和有几个空格(如 <a> ...</a>
)。另外,内部空标签也应该被删除。例如
<p style="text-align:right;"> <a> </a> <a></a></p><p>Hello</p>
应该离开
<p>Hello</p>
因为删除空<a> </a> <a></a>
后一个空<p style="text-align:right;"> </p>
仍然会保留并应该被删除。
我在做什么:
$.(".container>*:empty").remove();
结果令人困惑。我已经开始使用这样的代码进行调试:
console.log($.(".container>*:empty").size());
1) 字符串:
Well, though it looks like a paragraph, it's not o_O.
0 (I'm wrapping string in global wrapper .container)
2) 字符串
<a></a><a>Well, though it looks like a paragraph, it's not o_O.</a>
1
3) 字符串
<a> </a><a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (It seems one whitespace makes a non-empty)
4) 字符串
<p> <a></a></p> <a>Well, though it looks like a paragraph, it's not o_O.</a>
0 (<a></a> is not selected as empty (maybe 'cause it's inside of < p>).
Also p is not selected, besides it contains only empty < a>)
我的问题是:
- 如何制作
:empty
选择两个空标签并带有 1-N 空格? - 如何制作
:empty
选择每个对象中的所有空标签?
我的想法是做${"*:empty"}.remove() while $('*:empty').size() > 0
.
更新:
do {
$(".container *").filter(function() {
return $.trim(this.innerHTML) === ""
}).remove();
} while ($(".container *").filter(function() {
return $.trim(this.innerHTML) === ""
}).size() > 0)
console.log($(".container").html())
将此代码应用于:
<p> <p> <a> <a> <a><br><hr></a> </p> <a>Well, though it looks like a paragraph, it's not o_O.</a></p>
我们得到:
<p> <a>Well, though it looks like a paragraph, it's not o_O.</a></p>
最佳答案
$(".container *")
.filter(function(){
return $(this).is(':not(br)')
&& $(this).is(':not(img)')
&& $.trim(this.innerHTML) === ""
}).remove();
关于jquery - jQuery "empty:"-选择器如何工作? (删除空标签),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16043693/