我想用jQuery删除div中的最后<BR>
个。我尝试了这段代码,但它也删除了第一个和中间的换行标记。
HTML代码
<div class="topic">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.<br/>
Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes,<br/>
nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
Nulla consequat massa quis enim. DonecLorem ipsum dolor sit amet, consectetuer adipiscing elit.<br/>
<br/>
<br/>
<br/>
</div>
jQuery代码
$(document).ready(function(){
$('.topic').find('br').remove();
});
答案 0 :(得分:2)
一种可能的方法:
// selecting the <br /> element that is a last-child:
$('br:last-child')
// selecting all previous-sibling elements until we find one that is not a <br /> element:
.prevUntil(':not(br)')
// adding the initial selector back to the collection:
.addBack()
// filtering the collection:
.filter(function() {
var sibling = this.previousSibling;
// keeping only those <br /> elements with a previous-sibling of nodeType === 3
// (a textNode), and those whose previous-sibling's nodeValue (with leading
// and trailing white-space removed) is equal to 0:
return sibling.nodeType === 3 && sibling.nodeValue.trim().length === 0;
// removing those elements:
}).remove();
$('br:last-child').prevUntil(':not(br)').addBack().filter(function() {
var sibling = this.previousSibling;
return sibling.nodeType === 3 && sibling.nodeValue.trim().length === 0;
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="topic">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
<br />Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes,
<br />nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. DonecLorem ipsum dolor sit amet, consectetuer adipiscing elit.
<br/>
<br/>
<br/>
<br/>
</div>
参考文献:
答案 1 :(得分:2)
我知道这不是你问的,但我想你正试图去掉额外的视觉休息。如果是这样的话,用css做它就不那么有影响了:
br + br{display:none;}
这将使第一个休息时间休息,而所有兄弟姐妹都被隐藏。
答案 2 :(得分:1)
我从未使用它,但这应该有效:
$(document).ready(function() {
$('.topic').find('br:last-child').remove();
}
答案 3 :(得分:0)
$(document).ready(function(){
$('.topic').find('br:last').remove();
});
使用:last
选择器,它将采用最后一个匹配的元素。
答案 4 :(得分:0)
以$('br').remove();
为例:jsfiddle
答案 5 :(得分:0)
这对我有用:
$('#customID br:last-child').remove();
从自定义标记中删除最后一个br标记。
注意:我使用过Jquery 3.1.1版