[英]finding closest sibling in jQuery
I have the following code in HTML:我在 HTML 中有以下代码:
$(".remove-post").click((event) => { $(event.target).fadeOut(); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <button class="remove-post"> delete </button> <a class="list"> <p>post title</p> </a> <button class="remove-post"> delete <button> <a class="list"><p>another post title</p></a> </div>
every time that I click on a delete button I want to delete the closest "a" tag with the paragraph inside it as well as the delete button by itself.每次单击删除按钮时,我都想删除其中包含段落的最接近的“a”标签以及删除按钮本身。 I was able to delete the button but can't target the closest a tag to that clicked button I wrote it in jQuery
我能够删除按钮,但无法定位与单击按钮最近的标签我在 jQuery 中编写了它
If the button will always stay before paragraph you can do:如果按钮将始终停留在段落之前,您可以执行以下操作:
$(".remove-post").on("click", function () {
$(this).next(".list").fadeOut()
$(this).fadeOut()
})
I would recommend you to wrap the paragraph and the button together like:我建议您将段落和按钮包装在一起,例如:
<div class="side-bar">
<div class="wrapper">
<button class="remove-post">Delete<button>
<a class="list">Another post title</a>
</div>
<div class="wrapper">
<button class="remove-post">Delete <button>
<a class="list">Another post title</a>
</div>
</div>
If you do so, then you can use this:如果你这样做,那么你可以使用这个:
$(".remove-post").on("click", function () {
$(this).parent().fadeOut()
})
Assuming you want to remove the next a.list
sibling, use .next()假设您要删除下一个
a.list
兄弟,请使用.next()
$(".remove-post").on("click", function() { const btn = $(this) btn.add(btn.next("a.list")).fadeOut() })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="side-bar"> <button class="remove-post">delete</button> <a class="list"><p>post title</p></a> <button class="remove-post">delete</button> <a class="list"><p>another post title</p></a> </div>
jQuery's .add() is used here to collect both the <button>
and <a>
so you can fade them out together. jQuery 的.add()在这里用于收集
<button>
和<a>
以便您可以将它们一起淡出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.