【发布时间】:2018-09-30 16:56:14
【问题描述】:
我有一个投票按钮,在我看来应该会立即改变颜色和计数。通过按钮触发的后端功能应该在后端处理,因此用户无法识别它。问题是,如果我使用 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);
}
【问题讨论】:
-
老兄,使用框架。
-
你能推荐一个吗?
-
我不知道你的整个结构,你的 web 应用程序要做什么,但对我来说,常青的选择总是 React。选择 react 意味着了解关注点的分离,这在开发中很重要,基本上可以帮助您不要失去理智。
-
我不知道如何解决我的反应问题,从来没有使用过。我正在使用 laravel 5.7,它提供了开箱即用的 vue.js,但从未使用过它。