Meteor - 如果标记嵌套在{{#with}}块中,则DOM查询不起作用

时间:2015-08-07 23:44:49

标签: javascript jquery meteor

HTML

<template name="formExample">
  <form>
  {{#with formData}}

    <input type="text" class="example">

  {{/with}}
  </form>
</template>

JS

Template.formExample.helpers({
  'formData': function() {
    return Settings.findOne({ collection_id : getCollectionId() })
  }
})


Template.formExample.rendered = function(){

  // Does not work
  console.log( $('.example'), document.querySelectorAll('.example') )
  // >> undefined []

  // Works (but obviously bad)
  setTimeout(function() {
    console.log( $('.example') )
  }, 1000)

  // Does not work
  console.log( this.$('.example'), this.find('.example') )

  // >> [prevObject: jQuery.fn.init[0], context: li] null
}

如何使用逻辑块内的代码有效地查询DOM,init函数等?我希望template.$template.find方法能够正常运行。

2 个答案:

答案 0 :(得分:0)

您在哪里设置formData? 我试过你的例子,它似乎有效。

测试:http://meteorpad.com/pad/tXKpZ6gxpGur5pDds

答案 1 :(得分:0)

我发现有时它也有效,所以也许这是一个更好的解决方案。

<强> HTML

<template name="formExample">
  <form>
    {{#with formData}}
      {{> formExampleItems}}    
    {{/with}}
  </form>
</template>

<template name="forExampleItems">
  <input type="text" class="example">
</template>

<强> JS

Template.forExampleItems.onRendered(function(){
  console.log(this.$('.example'));
  ...
})