我有一个带有文本的页面,但是有些容器有空段落标记,每个容器都在末尾。重要的是我不要删除内容之间的任何内容,只是在文本结束后才结束。我的想法是首先遍历容器,然后以相反的顺序检查所有段落标记,删除任何与正则表达式匹配的内容以及当它遇到某些内容时 - 转到下一个元素。我为此创建了一个jsfiddle,但它只从最后一个面板中删除它们。
jquery的
$(document).ready(function() {
$(".content").each(function() {
$($("p").get().reverse()).each(function() {
var $this = $(this);
if ($this.html().replace(/\s| /g, '').length == 0) {
$this.remove();
}
else {
return false;
}
});
});
});
HTML
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
</div>
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
<p>another paragraph</p>
<p> </p>
<p> </p>
<p> </p>
</div>
https://jsfiddle.net/659Lejgz/1/
我觉得自己如此接近,但它只是我无法触及的。任何帮助都会非常棒!
答案 0 :(得分:2)
您需要更改$($("p").get().reverse()).each(function() {
收件人:$($(this).find("p").get().reverse()).each(function() {
实际上,当原始代码发生时,虽然我们循环遍历.content
元素,但在循环的每次迭代中,我们在整个文档的上下文中查询p
元素,因为我们反转结果,所以我们总是得到最后一个p
元素的最后一个.content
元素。
通过将$("p")
更改为$(this).find("p")
,我们强制jQuery仅在我们当前正在迭代的p
元素内搜索.content
元素。
答案 1 :(得分:1)
您的代码存在两个问题。首先,您需要为要循环的内容div指定段落 relative ,否则您将它们视为一组。另一个问题是当你向后循环并且击中每个div中的第一个非空段时,实际删除需要停止。
这应该可以解决问题:
$(".content").each(function() {
$($("p", this).get().reverse()).each(function() {
if ($.trim($(this).text()).length === 0) {
$(this).remove();
} else {
return false;
}
});
});
.content {
background-color: red;
border: 1px solid black;
font-size: 18px;
margin-bottom: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
</div>
<div class="content">
<p>Blah</p>
<p> </p>
<p> </p>
<p>Another Paragraph I want to keep</p>
<p> </p>
<p> </p>
<p>another paragraph</p>
<p> </p>
<p> </p>
<p> </p>
</div>
答案 2 :(得分:0)
在此处添加this
: -
$($("p", this).get().reverse()).each(function() {
这指定了.content
each
的上下文
jQuery(selector [,context])