假设我有一个名为 message 的 Meteor 模板,客户端可以在其中发布消息。该帖子被包装在一个 div 中,该 div 的 id 等于其在 Mongo 集合中的唯一 id。
<template name="message">
<div class="msg comment" id="{{this._id}}">{{msg}}</div>
</template>
有没有办法在Meteor.message.rendered
中引用特定的id?现在我正在使用 this._id
但它不起作用。这是我的功能
Template.message.rendered = function() {
texts = $('this._id').html();
texts = texts.replace(/#(\w+)/g,
"<a href='https://www.google.com/?q=$1'target='_blank'>$&</a>");
$("this._id").html(texts);
}
最佳答案
四件事:
- 您使用的是字符串而不是变量:
$('this._id')
->$(this._id)
- 渲染函数的上下文 (
this
) 是模板助手,而不是数据本身(这是模板的上下文),因此替换this._id
与this.data._id
匹配{{ this._id }}
- 这是一个 ID 选择器:
$(this.data._id)
->$('#' + this.data._id)
- 每当重新渲染模板以及渲染子模板(模板中包含的模板)时,渲染回调都会运行,因此您应该在渲染它时进行标记( source ,有关 meteor 渲染的有趣文章)。
最终代码:
Template.message.rendered = function() {
if(!this.rendered) {
this.rendered = true;
texts = $('#' + this.data._id).html();
texts = texts.replace(/#(\w+)/g,"<a href='https://www.google.com/?q=$1'target='_blank'>$&</a>");
$('#' + this.data._id).html(texts);
}
}
关于javascript - 使用 'this' 引用与meteor.template.rendered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31439583/