查询:当$(this)在另一个div中时,如何遍历到上一个div及其子级



这是我迄今为止尝试的代码:

因此,当我点击a链接(它有一个类'.like'(时,我希望('.PostlikeCount'[在div.postInfo]中找到](显示新的总赞量。

$(".like").click(function(e) {
e.preventDefault()
$.ajax({
method: "GET",
url: $(this).attr("href"),
success: function(response) {
console.log(response)
$(this).parents("div.row").prevAll().first().find("span.PostlikeCount").html(response.total_likes)
}
});
});
<div class="row postInfo">
<small class="font-weight-light col-8 ">
<span class="PostlikeCount">{{post.likePost.count}}</span> people like this 
</small>
<small class="font-weight-light ml-3 viewAll"><a href= "#">view all comment</a>
</small>
</div>
<hr>
<div class="mt-2 row">
<span class="col-9 postLike">
<a href="{%url 'likes:like_Post' post_id=post.id location='homePage'%}" class="d-inline-block like">
<span><i class="far fa-heart "></i> Like</span>
</a>
</span>
</div>

假设:

  • 您有多个.postInfo.mt-2对,而不仅仅是问题中的一对
  • 你不能将postInfo/mt-2包装在另一个类中(这会让这变得更容易(

您需要获取离单击的链接最近的.row,然后使用.prevAll(".postInfo")查找相关的postInfo,然后在下面查找以获取PostLikeCount。

你的代码和这个之间的区别是

.prevAll(".postInfo")

将提供所有以前的".postInfo"节点,而不是所有以前的节点。当使用.prevAll时,它们的顺序相反,因此.first()将正确地在HTML中找到上面的那个。

第二个区别是.closest(".row")将找到第一个是.row的父级。很可能您的代码不起作用,因为您已经嵌套了.rowdiv(问题中没有显示(,但您只想要与.postInfo处于同一级别的

我删除了不相关的ajax调用,以提供一个工作片段。

$(".like").click(function(e) {
e.preventDefault()
$(this)
.closest("div.row")
.prevAll(".postInfo")
.first()
.find("span.PostlikeCount").html($(this).data("result"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row postInfo">
<small class="font-weight-light col-8 ">
<span class="PostlikeCount"><em>result here</em></span> people like this 
</small>
<small class="font-weight-light ml-3 viewAll"><a href= "#">view all comment</a>
</small>
</div>
<hr>
<div class="mt-2 row">
<span class="col-9 postLike">
<a href="#" class="d-inline-block like" data-result='11'>
<span><i class="far fa-heart "></i> Like</span>
</a>
</span>
</div>
<div class="row postInfo">
<small class="font-weight-light col-8 ">
<span class="PostlikeCount"><em>result here</em></span> people like this 
</small>
<small class="font-weight-light ml-3 viewAll"><a href= "#">view all comment</a>
</small>
</div>
<hr>
<div class="mt-2 row">
<span class="col-9 postLike">
<a href="#" class="d-inline-block like" data-result='22'>
<span><i class="far fa-heart "></i> Like</span>
</a>
</span>
</div>

最新更新