jquery - 与后台投票功能同步投票按钮
问题描述
我有一个投票按钮,在我看来应该立即改变颜色和计数。通过按钮触发的后端功能应该在后端处理,因此用户无法识别它。问题是,如果我使用 jquery 更改视图中按钮的颜色,如果用户非常快地按下按钮,这将与后端功能不同步。所以我想知道如何处理这个?如果我使用 ajax 响应来做这件事需要很长时间......这不是一个好的用户体验。我希望你们明白我的意思吗?
<a data-id="{{ $article->id }}" class="vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'active' : '' }}"></a>
<div class="points">{{ $article->votes->count() }}</div>
我想用来改变按钮颜色并在我的视图中计数的脚本
$(document).on('click', '.vote', function() {
var $counter = $(this).parent().find('.points');
$(this).toggleClass('active');
if($(this).hasClass('active')) {
$counter.html(parseInt($counter.text(), 10) + 1);
} else {
$counter.html(parseInt($counter.text(), 10) - 1);
}
var $button = $(this);
$button.addClass('vote-live');
var id = $button.data('id');
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{!! URL::to('article/vote/') !!}/" + id,
dataType: 'JSON',
data: {
"_method": 'POST',
"_token": token,
"id": id,
},
success: function(data) {
$counter.html(data.count);
$button.removeClass('vote-live');
// var color = data.voted ? 'transparent transparent #a53031 transparent' : 'transparent transparent #a53031 transparent';
// $button.css('border-color', color);
console.log('success');
console.log(data);
},
error: function(xhr) {
$button.removeClass('vote-live');
if (xhr.status == 401) {
window.location.href = "{!! URL::to('login') !!}";
} else if (xhr.status == 403) {
window.location.href = "{!! URL::to('email/verify') !!}";
}
},
});
});
它喜欢这样,但不知道那是不是要走的路?看起来有点不专业,但我不知道它通常是怎么做的......
$(this).toggleClass('active');
if($(this).hasClass('active')) {
$counter.html(1);
} else {
$counter.html(0);
}
解决方案
这里的解决方案是在服务尚未完成时禁用按钮。为此,您只需.is-sending
在用户单击按钮时添加类名,这是 CSS:
.is-sending {
pointer-events: none; // prevents the pointer event, so they cannot click
cursor: default;
opacity: 0.6;
}
然后在success
你删除那个类名。我强烈建议你应该使用button
元素而不是a
元素,在这种情况下你可以使用disabled
属性而不是.is-sending
类名。
推荐阅读
- wordpress - Woocommerce 创建订单 API 问题
- c# - .net 模拟未将正确的凭据传递给 SQL Server
- javascript - jQuery Uncaught TypeError: $(...).editRule is not a function - click 事件
- ruby - tar -C 在 Chef 中失败
- c - Spectre 警告 MSVC C5040 的解决方法
- ruby-on-rails - 如何使用 RubyMine、Rails 和 Docker(远程 SDK)?
- terraform - 将字符串附加到 Terraform 中的地图类型
- ruby - 乘客-Sinatra:机架/显示异常(LoadError)
- java - 计算时差
- wordpress - Wordpress Avada:如何创建多行列