【问题标题】:Up and Downvote button向上和向下投票按钮
【发布时间】:2016-05-14 13:56:03
【问题描述】:

我尝试实现一个向上或向下投票按钮,用户只能投票 1 次向上和 1 次向下投票。如果您已经对某些内容进行了投票,则应该可以通过再次单击“投票”按钮将其删除,但我不知道缺少什么。我的代码如下所示。我想我必须用真实的虚假陈述来实现一些东西,但我尝试了一些东西但没有任何效果。非常感谢您的帮助!

Template.postArgument.events({
 'click':function() {
  Session.set('selected_argument', this._id);
  },
 'click .yes':function() {
          if(Meteor.user()) {
            var postId = Arguments.findOne({_id:this._id})
            console.log(postId);
            if($.inArray(Meteor.userId(), postId.votedUp) !==-1) {
              return "Voted";
            } else {
        var argumentId = Session.get('selected_argument');
        Arguments.update(argumentId, {$inc: {'score': 1 }}); 
        Arguments.update(argumentId, {$addToSet: {votedUp: Meteor.userId()}});
            }
          }
  }});

【问题讨论】:

  • 这在语法上无效...您不要用右括号关闭 click 事件的函数。要么你在粘贴过程中遗漏了一些东西,要么你有一些语法问题需要解决,然后才能达到你的预期。
  • 只是复制粘贴失败;)
  • 因此,换句话说,您需要两个看起来像投票按钮的复选框。

标签: javascript meteor vote-up-buttons


【解决方案1】:

您的一般方法是正确的,但是您根本不需要 Session 变量,甚至不需要第一次点击处理程序。而且您根本不需要从函数中返回任何内容。

Template.postArgument.events({
  'click .yes': function(){
    if ( Meteor.user() ) {
      var post = Arguments.findOne({_id:this._id});
      if ( $.inArray(Meteor.userId(), post.votedUp) === -1 ) {
        Arguments.update(this._id, {
          $inc: { score: 1 },
          $addToSet: { votedUp: Meteor.userId() }
        }); 
      } else {
        Arguments.update(this._id, {
          $inc: { score: -1 },
          $pull: { votedUp: Meteor.userId() }
        }); 
      }
    }
  }
});

【讨论】:

  • 但如果我再次点击 .yes 按钮,我如何才能删除我最后的 +1 分数?
【解决方案2】:

您可以通过检查用户是否存在赞成票和反对票并相应地增加/减少然后将用户添加到集合中来开始简单的操作。

Meteor.methods({
  'downvote post': function (postId) {
    check(postId, String);
    let post = Posts.findOne(postId);

    Posts.update(postId, post.downvoters.indexOf(this.userId !== -1) ? {
      $inc: { downvotes: -1 },               // remove this user's downvote.
      $pull: { downvoters: this.userId }     // remove this user from downvoters
    } : {
      $inc: { downvotes: 1 },                // add this user's downvote
      $addToSet: { downvoters: this.userId } // add this user to downvoters.
    });
  }
});

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多