Meteor:在点击事件中将类添加到表元素中

Meteor: adding a class to a table element on a click event

本文关键字:添加 元素 Meteor 事件      更新时间:2023-09-26

我有一个包含一些表行的表,因此我创建了一个单击事件,当单击特定的td元素时,它会更新myCollection,这很好。我想做的是显示一个引导程序"勾号",以显示单击时该元素是"活动的"。

如果我在控制台上运行$('.activate').addClass('glyphicon glyphicon-ok');,它会将类添加到具有.activate类的所有元素中,而不是触发事件的元素。我也可以从下面的函数中运行这一行,得到相同的结果。

使用以下代码,我似乎根本无法做到这一点:

'click .activate': function (event, template) {
     var id=event.target.getAttribute("data-id");
      myCollection.update({_id: id}, {$set: {status: "active"}});
      // I've tried variations of the line below with no success
      $(this).closest("td").addClass("glyphicon glyphicon-ok");
 }

此外,当页面重新加载时,我希望在正确的位置显示"勾号"。我不知道怎样做才是最好的。我不能这样做,例如:

{{#each myCollection}}
  {{#if status=="active"}}
     <p>display stuff</p>
  {{/if}}
{{/each}}

你知道我该怎么做吗?

提前感谢:)

在事件处理程序内部,this是被单击的元素的上下文,而不是元素本身。更"迅速"的方法是使用反应性而不是jQuery来更新DOM。

<template name="table">
  {{#each myCollection}}
    {{> tr}}
  {{/each}}
</template>
<template name="tr">
  <td class="activate">Activate</td>
  <td>
    {{#if active}}
    <span class="glyphicon glyphicon-ok"></span>
    {{/if}}
  </td>
</template>
Template.table.myCollection = function () {
  return myCollection.find();
};
Template.tr.active = function () {
  return this.status === "active";
};
Template.tr.events({
  'click .activate': function (event, template) {
    myCollection.update(this._id, {$set: {status: "active"}});
  }
});

如果你正在处理一个持久状态(这里似乎是这样),Neil的答案是正确的。

如果你只是需要一些临时的UI效果,你可以使用以下jQuery:

$(event.target).addClass("glyphicon glyphicon-ok");

(与您尝试的代码几乎相同,但使用$(event.target)而不是$(this)