[英]onRendered cannot find element in Meteor
我有一个模板
{{#if hasItems}}
<ul id="myId">
{{#each items}}
{{> item}}
{{/each}}
</ul>
{{else}}
<p>No items</p>
{{/if}}
和
Template.itemList.onRendered( function () {
var el = this.find( '#myId' );
} );
但由于模板最初没有任何项目,因此从未找到id="myId"
的元素,因此呈现模板时元素<ul id="myId">
不存在。
如何确保渲染时元素存在?
我猜我可以放var el = this.find( '#myId' );
在Tracker.autorun
内部或制作嵌套模板
<template name="hasItems">
<ul id="myId">
{{#each items}}
{{> item}}
{{/each}}
</ul>
</template>
并在hasItems
为true时包括此模板,然后对hasItems
使用onRendered
代替外部模板。
但这不是丑陋的骇客吗?
这是你应该做的
范本
<template name="itemList">
{{#if hasItems}}
{{> showItems }}
{{else}}
<p>No items</p>
{{/if}}
</template>
<template name="showItems">
<ul id="myId">
{{#each items}}
{{> item}}
{{/each}}
</ul>
</template>
渲染处理程序
Template.itemList.helpers({
hasItems: function() {
// do you have items?
}
});
Template.showItems.onRendered(function (){
var el = this.find( '#myId' );
});
Template.showItems.helpers({
items: function() {
// return the items
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.