简体   繁体   English

onRendered在流星中找不到元素

[英]onRendered cannot find element in Meteor

I have a template 我有一个模板

{{#if hasItems}}
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
{{else}}
  <p>No items</p>
{{/if}}

and

Template.itemList.onRendered( function () {
  var el = this.find( '#myId' );
} );

but the element with id="myId" was never found because the template intially has no items, so the element <ul id="myId"> does not exists when the template was rendered. 但由于模板最初没有任何项目,因此从未找到id="myId"的元素,因此呈现模板时元素<ul id="myId">不存在。

What can I do to make sure the element exists when rendered? 如何确保渲染时元素存在?

I guess I can either put var el = this.find( '#myId' ); 我猜我可以放var el = this.find( '#myId' ); inside Tracker.autorun or make a nested template Tracker.autorun内部或制作嵌套模板

<template name="hasItems">
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
</template>

and include this template when hasItems is true and then use onRendered for hasItems instead of the outer template. 并在hasItems为true时包括此模板,然后对hasItems使用onRendered代替外部模板。

but isn't it a bit ugly hack? 但这不是丑陋的骇客吗?

Here's what you should do 这是你应该做的

Templates 范本

<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>

Render Handler 渲染处理程序

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM