【发布时间】:2016-12-11 02:48:57
【问题描述】:
我正在尝试使用计数器实现喜欢/不喜欢系统。我的 AJAX 调用出现问题,更具体地说,当我在将值传递给数据库后尝试更改视图中选定元素的 HTML 时。
有问题的元素是 .likeCount,一个有大约十几个兄弟姐妹的类。如果我简单地使用选择器 $('.likeCount'),AJAX 调用实际上会成功更新喜欢计数,但它会为类的每个实例执行此操作。如果我尝试使用 DOM 遍历(.closest、this、.parent 等),在我刷新页面之前,类似计数不会更新。
赞成票和反对票带有 $('like') 类。
$(document).ready(function()
{
$('.like').on('click', function(event)
{
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
$.ajax(
{
method: 'POST',
url: urlLike,
cache: false,
data: {isLike : isLike, postId : postId, _token : token},
success: function()
{
//first function working great
//(changes the like button to a disklike button and visa versa)
$.ajax(
{
method: 'POST',
url: urlCount,
cache: false,
data: {postId : postId, _token : token},
dataType: 'json',
async: true,
success: function(data)
{
var likeCount = event.target.parentNode.parentNode.childNodes[2].textContent;
$('likeCount').html(data["count"]);
console.log(data["count"]);
}
})
}
})
})
})
console.log 每次都会输出正确的计数。
如何选择当前活动的 likeCount 而不会破坏我的 AJAX 调用?
这里是标记:
<div class="row posts">
<div class="col-md-6 col-md-offset-3">
<header><h3>Recent Posts:</h3></header>
@foreach($posts as $post)
@if (Storage::disk('local')->has($post->user->id . '.jpg'))
<div class="col-xs-2">
<img src="{{ route('account.image', ['filename' => $post->user->id . '.jpg']) }}" alt="" class="img-responsive">
</div>
@else
<div class="col-xs-2">
<img src="default.gif" alt="" class="img-responsive">
</div>
@endif
<article class="post col-xs-10" id="post" data-postid={{ $post->id }}>
<p class="post-body">{{ $post->body }}</p>
<div class="info">
Posted by {{ $post->user->name }} on {{ $post->created_at }}
</div>
<div class="likeCount">{{ $post->likes->where('like', '1')->count() }} other people liked this.</div>
<div class="interaction">
<a class="like btn upvote">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ? 'You like this' : 'Like' : 'Like'}}</a> |
<a class="like btn downvote">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ? 'You dislike this' : 'Dislike' : 'Dislike'}}</a>
@if(Auth::user() == $post->user)
|
<a href="#" class="edit">Edit</a> |
<a href="{{ route('post.delete', ['post_id' => $post->id]) }}">Delete</a>
@endif
</div>
</article>
@endforeach
<?php echo $posts->links(); ?>
</div>
</div>
【问题讨论】:
-
你的第二个电话不应该在成功函数中吗?
-
不要使用 $('likeCount'),使用 $(event.target.parentNode.parentNode.childNodes[1]) 或类似的东西
-
@Sandesire,谢谢,这是一个错字。
-
@juvian 我试过了,不幸的是它到目前为止还没有工作。
-
我认为您应该将 html 添加到问题中。由于内部success函数中的log是正常工作的,看来你的问题确实是关于正确遍历DOM的问题,所以html结构是关键。
标签: javascript jquery html ajax dom