使用 JS 更改 Meteor 中的按钮文本

Change button text in Meteor with JS

我的按钮点击显示和隐藏 div 包含评论部分。现在我想让他在点击时更改文本。所以,你点击一次,你可以看到评论,但现在需要 'Hide comments' 而不是 'Show comments' 他的文本。我尝试了几种在互联网上找到的解决方案以及一些对我来说合乎逻辑但没有用的解决方案。我也试过 但它说 SetSession 未定义。

模板:

<template name="PrikažiMe">

<button class="PrikažiKomentar"> {{текст}} </button>

</template>

JS

if (Meteor.isClient) {


  /*  Template.PrikažiMe.onCreated(function() {
        Session.set(текст , 'Прикажи коментаре');  // <---- This part makes like everything is unpublished
    }); */


    Template.PrikažiMe.events({
      'click .PrikažiKomentar': function(){

        if (document.getElementById(this._id).style.display == "none") 
            { document.getElementById(this._id).style.display = "inline-flex", SetSession (текст, 'Сакриј коментаре');}
        else {document.getElementById(this._id).style.display = "none", SetSession (текст, 'Прикажи коментаре'); }
      }, 
    });  

    Template.PrikažiMe.helpers({   
      текст: function(){
        return Session.get(текст);
      },
    });      
};

您不应从 JavaScript 更改 HTML/CSS,而应在您的模板中处理它。

这是一个未经测试代码的示例。它还依赖于包 reactive-var.

<template name="t">
  <button id="b">{{#if isButtonActive}}Active!{{else}}Not active{{/if}}</button>
</template>
Template.t.onCreated(function(){
  this.isButtonActiveReactiveVar = new ReactiveVar(false)
})

Template.t.helpers({
  'isButtonActive': function(){
    return Template.instance().isButtonActiveReactiveVar.get()
  }
})

Template.t.events({
  'click #b': function(event, template){
    template.isButtonActiveReactiveVar.set(!template.isButtonActiveReactiveVar.get())
  }
})

所以,我发现了问题所在。希望这会在将来帮助某人。看代码:

模板:

<button class="PrikažiKomentar"> {{#if текст}}Сакриј коментаре {{else}} Прикажи коментаре {{/if}} </button>

</template>

JS:

if (Meteor.isClient) {

    Template.PrikažiMe.onCreated(function PrikažiMeOnCreated() {
        this.текст = new ReactiveVar(false);
    }); 

    Template.PrikažiMe.events({
      'click .PrikažiKomentar': function(event, template){
        if (document.getElementById(this._id).style.display == "none") 
            { document.getElementById(this._id).style.display = "inline-flex", template.текст.set( true );}
        else {document.getElementById(this._id).style.display = "none", template.текст.set( false );}
      }, 
    });  

   Template.PrikažiMe.helpers({   
       текст: function() {
              return Template.instance().текст.get();
       },
    });      
};