我在这里有这个HTML代码:
<div class="container">
<section>
<header class="date">May 2014</header>
<article>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit</article>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime.</article>
<article>ratione mollitia expedita tempore reprehenderit maxime.</article>
<a href="#">Remove Article</a>
</section>
<section>
<header class="date">March 2014</header>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime unde quas beatae maiores.
</article>
<a href="#">Remove Article</a>
</section>
<section>
<header class="date">April 2014</header>
<article>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</article>
<article>Repellendus, dolorem, laborum non illum voluptate vitae quibusdam impedit aperiam placeat minus ratione mollitia expedita tempore reprehenderit maxime unde quas beatae maiores.
</article>
<a href="#">Remove Article</a>
</section>
</div>
当我点击&#39;删除文章&#34;链接我应该删除其上面的一篇文章。我有这个。
现在,我想在这里完成的是,当我逐一删除所有文章时,#39;属于特定部分我需要自动获得标题&#39; date&#39;和链接&#39;删除文章&#39;完全删除。
我尝试了不同的方法,但我仍然可以看到标题和链接,但是当我刷新页面时它们就消失了。
答案 0 :(得分:2)
我想我找到了你。如果没有删除整个article
,您是要逐个删除section
吗?如果是这样,这应该有效:
$('a').on('click', function (e) {
e.preventDefault();
var $section = $(this).closest('section'),
$articles = $section.find('article');
$articles.last().remove();
// $articles.length will not be one less just because we removed
// an item, so just checking for 1 here is the same as checking
// if it's empty.
if ($articles.length === 1) {
$section.remove();
}
});
答案 1 :(得分:1)
您是否尝试将this.parentElement.remove()绑定到html中的元素?它将删除整个部分。
$('.container a').click(function(){
this.parentNode.remove()
}
答案 2 :(得分:1)
$('section a').on('click', function(e) {
e.preventDefault();
var self = $(this);
var articles = self.siblings('article');
if (articles.length > 1) {
articles.last().remove();
}
else {
self.parent().remove();
}
})
答案 3 :(得分:0)
更新:删除每篇文章,直到只剩下一篇文章,然后删除上一篇文章和部分。感谢@Barmar指出我的错误。
$('body').on('click', '.container a', function (e) {
e.preventDefault();
var articleLength = $(this).closest('section').find('article').length;
if (1 != articleLength) {
$(this).closest('section').find('article:last').remove();
} else {
$(this).closest('section').remove();
}
});