【问题标题】:jquery empty - remove html tag if no contentsjquery empty - 如果没有内容,则删除 html 标签
【发布时间】:2017-03-10 04:03:33
【问题描述】:

jquery empty - 如果没有内容则删除 html 标签

如果html标签不包含文本或内容,如何删除它。

如果使用<p></p> 代码有效, 但 如果使用

<p>

</p>

代码不成功

jquery

$(document).ready(function(){
    $("button").click(function(){
        $('#demo p:empty').remove();
    });
});

html

<p>

</p>
==================================

$(document).ready(function(){
    $("button").click(function(){
		$('#demo p:empty').remove();
    });
});	 
  p {
    background:red;
    color:white;
    height:20px;
  }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
</head> 
<body>
  
<button>Run</button>	
<div id='demo'>
  <p>
  
  </p>
  <p>
    Lorem Ipsum .....
  </p>
</div>

</body>
</html>

提前致谢

【问题讨论】:

  • 中可能有什么?
  • 只需从

    标记中删除空格或在删除修剪值之前。

标签: javascript jquery html


【解决方案1】:

$(document).ready(function() {
  $("button").click(function() {
    $('#demo p').filter(function() {
      return $(this).html().trim().length == 0
    }).remove();
  });
});
p {
  background: red;
  color: white;
  height: 20px;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>

<body>

  <button>Run</button>
  <div id='demo'>
    <p>

    </p>
    <p>
      Lorem Ipsum .....
    </p>
  </div>

</body>

</html>
  1. 将 filter() 与 html() 和 trim() 一起使用
  2. trim() 删除空格

【讨论】:

  • @SisiSajah 很高兴为您提供帮助 :)
【解决方案2】:
$('#demo p').each(function(){
 if(!$(this).text() || !$(this).text().trim())
   $(this).remove();
})

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多