我有一个包含几行表格的表格,因此我创建了一个更新 myCollection
的点击事件特别的时候td
单击元素,这工作正常。我想要做的是显示一个 Bootstrap “勾号”,以表明该元素在单击时处于“事件”状态。
如果我运行 $('.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
是被单击元素的上下文,而不是元素本身。更“快速”的方法是使用 react 性而不是 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"}});
}
});
关于javascript - meteor :在单击事件中将类添加到表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923153/