Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript onRendered在Meteor中找不到元素_Javascript_Jquery_Node.js_Templates_Meteor - Fatal编程技术网

Javascript onRendered在Meteor中找不到元素

Javascript onRendered在Meteor中找不到元素,javascript,jquery,node.js,templates,meteor,Javascript,Jquery,Node.js,Templates,Meteor,我有一个模板 {{#if hasItems}} <ul id="myId"> {{#each items}} {{> item}} {{/each}} </ul> {{else}} <p>No items</p> {{/if}} 但是找不到具有id=“myId”的元素,因为模板最初没有项目,因此呈现模板时元素不存在 如何确保渲染时元素存在 我想我可以把var el=this.find('#myId')

我有一个模板

{{#if hasItems}}
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
{{else}}
  <p>No items</p>
{{/if}}
但是找不到具有
id=“myId”
的元素,因为模板最初没有项目,因此呈现模板时元素
不存在

如何确保渲染时元素存在

我想我可以把
var el=this.find('#myId')内部
跟踪器。自动运行
或制作嵌套模板

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

您如何订阅这些数据?您可以在autorun中使用
subscriptionsReady()
来了解何时加载数据。im嵌套模板解决方案的方法是什么;)正如@MarkUretsky所说,您必须等待订阅准备就绪。你可以看看
<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
  }
});