3

我正在尝试从 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>
4

1 回答 1

4

你应该看看filter()trim()

演示

$(".container *")
    .filter(function(){
         return $(this).is(':not(br)') 
                && $(this).is(':not(img)') 
                && $.trim(this.innerHTML) === ""
     }).remove();
于 2013-04-16T17:52:22.627 回答