我正在使用名为 KindEditor 的所见即所得编辑器。我发现有时候它会额外添加一个<br>
自动地。我想知道如何删除多余的<br>
使用 jQuery。
例如,在下面的代码块中,我想删除第一个 <br>
放在代码块A和代码块B中,并保留在代码块C中。
代码块A
<p>
<br> <!-- it's useless now; need to remove -->
Taiwan next
<br>
Taichung goes global!
</p>
代码块B
<p>
<br> <!-- it's also useless now because the text before it's empty; need to remove -->
Taiwan next
<br>
Taichung goes global!
</p>
代码块C
<p>
New Taipei City
<br> <!-- The content before it is not empty, so it's useful; can not be removed -->
Taiwan next
<br>
Taichung goes global!
</p>
我想使用jQuery来做到这一点,我写了一个如下的选择:
$("p > br:first-child")
但它也会删除 <br>
在代码块 C 中,那么如何使用 jQuery 选择器来做到这一点?
虽然我们可以使用正则表达式来完成,但我想在 jQuery 中完成。
最佳答案
您可以使用filter
来检查前一个节点是否为空。
//console.log($("p > br:first-child"))
$('p > br:first-child').filter(function(){
return this.previousSibling.wholeText.trim() == "";
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p>
<br> <!-- it's useless now,need to remove -->
Taiwan next
<br>
Taichung goes global!
</p>
<p>
<br> <!-- it's also useless now due to the text before it's empty,need to remove -->
Taiwan next
<br>
Taichung goes global!
</p>
<p>
New Taipei City
<br> <!-- The content before it is not empty,so it's useful,can not be removed -->
Taiwan next
<br>
Taichung goes global!
</p>
关于javascript - 如何获取它们之间没有文本的第一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49809036/