根据用户是否投票设置布局样式

Set style in layout based on if user voted

本文关键字:设置 布局 样式 用户 是否      更新时间:2023-09-26

我制作了一个页面,人们可以在其中投票支持或反对论点。当他们登录时。但当他们投票给一个论点时,他们无法查看他们是否已经投票给了一个论点。例如,如果有超过1个人在列表中添加论点,你就看不出你是否已经投票。

我的代码是这样的:

Template.postArgument.events({
  'click .remove':function(event){
    var currentUserId = Meteor.userId();
    if(currentUserId === this.createdBy ) {
    event.preventDefault;
    var documentId = this._id;
    Arguments.remove({_id:documentId});
    }
  },
  'click':function() {
  Session.set('selected_argument', this._id);
  },
  'click .yes':function() {
      if(Meteor.user()) {
        var postId = Arguments.findOne({_id:this._id})
        if($.inArray(Meteor.userId(), postId.voted) !==-1) {
          return "Voted";
        } else {
    var argumentId = Session.get('selected_argument');
    Arguments.update(argumentId, {$inc: {'score': 1 }}); 
    Arguments.update(argumentId, {$addToSet: {voted: Meteor.userId()}});
        }
      }
  },
  'click .no':function() {
    if (Meteor.user())  {
      var postId = Arguments.findOne({_id:this._id})
      if ($.inArray(Meteor.userId(), postId.voted) !==-1) {
        return "Ok";
      } else {
      var argumentId = Session.get('selected_argument');
      Arguments.update(argumentId, {$inc: {'score': -1 }});
      Arguments.update(argumentId, {$addToSet: {voted : Meteor.userId()}});
      if (postId.score <= -3) {
        Arguments.remove({_id:this._id})
         }
       }
     }
  }
});

现在我想更改他们投票后点击的按钮的背景颜色。就像在Facebook上一样。但改变后的颜色应该只有投票人才能看到。对其他人来说,一切都不应该改变。这个possble怎么样?

我在var argumentId = Session.get('selected_argument');之后尝试了类似$(this).css('background-color', 'red');的东西但没有奏效。

不要将此作为一个操作,而是在您的模板中执行:

<div class="someBaseClass {{#if voted}}votedClass{{/if}}">
  ...rest of your html
</div>

然后创建一个助手,如果用户已经投票,则返回true。

Template.myTemplate.helpers({
  voted: function(){
    var argument = Arguments.findOne(){_id: this._id});
    return argument.voted.indexOf(Meteor.userId) > -1;
  }
});