0
我试图用计数器实现Like/Dislike系统。我遇到了AJAX调用问题,更具体地说,当我试图在将值传递给数据库之后更改视图中选定元素的HTML时。DOM遍历的AJAX调用遍历
有问题的元素是.likeCount,一个有大约十几个兄弟姐妹的类。如果我简单地使用选择器$('。likeCount'),那么AJAX调用实际上会成功更新类似计数,但它会为类的每个实例执行。如果我尝试使用DOM遍历(.closest,this,.parent等),直到刷新页面为止,类似的count才会更新。
up and downvote带有$('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而不会bot my我的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>
你的第二个电话不应该在成功功能? – sandrooco
不要使用$('likeCount'),使用$(event.target.parentNode.parentNode.childNodes [1])或者类似的 – juvian
@Sandesire,谢谢你的错误。 –