为什么我的<select>&#39; s <option>无法从Template.foo.rendered回调中访问?</option> </select>

时间:2015-04-08 00:33:41

标签: meteor

这是我的回调:

  Template.joinedRoomsList.rendered = function () {
    // the console.log prints: 'undefined' in client console
    console.log($('#joined-rooms').children().first().html());
    Session.set('currentRoom', $('#joined-rooms').children().first().text());
  }

这是我的模板:

<template name="joinedRoomsList">
  <select id="joined-rooms">
    {{#each joinedRooms}}
      <option>{{name}}</option>
    {{/each}}
  </select>
</template>

我尝试了很多不同的方法来设置会话密钥&#39; currentRoom&#39;到我的第一个值。

console.log语句在客户端控制台中打印出'undefined',但是,当我手动在开发人员控制台中输入相同的内容时:$('#joined-rooms').children().first().html(),它会给我一个值。< / p>

基本上,我试图设置会话密钥&#39; currentRoom&#39;到页面加载/主体加载/等的第一个值

2 个答案:

答案 0 :(得分:1)

您可以尝试通过调用defer来解决此问题。我猜你的方法太早了 - 在dom有时间渲染之前。

Template.joinedRoomsList.rendered = function () {
  Meteor.defer(function(){
    console.log($('#joined-rooms').children().first().html());
    Session.set('currentRoom', $('#joined-rooms').children().first().text());
  });
}

答案 1 :(得分:0)

尝试使用模板的选择器,它更有效率,因为我们只是在当前模板中找到元素而不是使用jQuery的整个厄运。

Template.joinedRoomsList.rendered = function() { 
   console.log(this.find("#joined-rooms"));
}