【问题标题】:Remove paragraphs with no text删除没有文字的段落
【发布时间】:2015-03-02 18:12:53
【问题描述】:

有没有办法可以删除其中没有文本但可能包含空 html 标签的段落?

例如

<p><strong><br></strong></p> or <p></p> or <p>&nbsp;</p>

将被删除,但

<p><strong>hi<br>there</strong></p> or <p>hi there</p>

不会被删除

【问题讨论】:

标签: javascript php regex preg-replace


【解决方案1】:

使用 jQuery 循环遍历所有 p 元素,然后只获取它的文本,修剪它(所以只有空格也会被删除),然后检查其中是否有文本,如果没有,删除它.

$('p').each(function() {
    if ($(this).text().trim() == "") {
        $(this).remove();
    }
});

jsfiddle 示例:http://jsfiddle.net/ygbnpg77/

【讨论】:

    【解决方案2】:

    如果你想用 javascript 做前端,你可以这样做。

    $(document).ready(function(){
        $('p').each(function(){
               if($(this).html().length == 0)
               {
                   $(this).remove();
               }
        })
    
    })
    

    【讨论】:

    • 如果段落包含标签,这将不起作用。给定&lt;p&gt;&lt;strong&gt;&lt;br&gt;&lt;/strong&gt;&lt;/p&gt;,$(this).html() 将等于&lt;strong&gt;&lt;br&gt;&lt;/strong&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多