我只需要在数据库中的 var 更改后加载这两个服务器变量。
现在,它们会在页面加载时立即加载,因此会保留事件发生前的值 (upvotesRef.transaction
)。
$('.HP').text("<%= post.upvotes - post.downvotes %> HP");
代码:
$('.UpvoteButton').click(function () {
var $this = $(this);
if ($this.hasClass("on")) {
$this.removeClass("on");
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
});
userRef.remove();
$('.HP').text("<%= post.upvotes - post.downvotes %> HP");
编辑:
我最终创建了局部变量来解决我的问题。谢谢您的回答!
var upvotesLocal = <%= post.upvotes %>;
var downvotesLocal = <%= post.downvotes %>;
$('.UpvoteButton').click(function () {
var $this = $(this);
if ($this.hasClass("on")) {
$this.removeClass("on");
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
});
upvotesLocal = upvotesLocal -1
userRef.remove();
$('.HP').text((upvotesLocal - downvotesLocal) + " HP")
最佳答案
您应该在交易后获取并更新变量吗?
这意味着它应该在您的回调中发生。
我假设您使用的是 firebase交易方式。
那么你的回调应该作为第二个参数:
$('.UpvoteButton').click(function () {
var $this = $(this);
if ($this.hasClass("on")) {
$this.removeClass("on");
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
}, updateVotes); //<-- here the callback function added
userRef.remove();
function updateVotes(error, isCommitted, upvotes) {
//here you got already your new upvotes
//but you should request the downvotes,
//here you need the ajax request, see e.g. Dez's answer or comments
}
关于javascript - 如何仅在特定事件后加载服务器变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444781/