【问题标题】:Meteor.js - setting focus to form input field upon template refactorMeteor.js - 在模板重构时设置焦点以形成输入字段
【发布时间】:2015-09-11 00:50:16
【问题描述】:

Meteor 新手,感谢任何帮助 - 一直在努力解决这个问题。所以我有一个有条件地绘制的模板:

{{#if creating}}
    <form class="form-create"> 
     <input name="name" type="text" id="mainInput">
     <button type="submit">Submit</button>
     <a class="cancel" href="#">Cancel</a>
     </form>
 {{else}}
   <a class="create" href="#">Create</a>
  {{/if}}

效果很好 - 单击锚链接通过“CREATING”会话反应变量调用表单,取消表单再次调用锚。

我的问题是当表单出现时,我想将输入 (#mainInput) 设置为焦点。现在,如果我将它连接到按钮或其他东西,这段代码将起作用(它将输入设置为焦点,所以我知道 jquery 有效 - 例如:

 "click .focusBtn": function(e, tpl) {

   tpl.$("#mainInput").focus();
   tpl.$("#mainInput").select(); //might as well select the entire thing too

},

但是,我无法将这个焦点“集中”在从锚点重绘到表单的屏幕上!

我已经尝试将它连接到会话变量 (Creating) 代码中 - 这样每次创建都会更改 (console.log 我看到 Creating 从 true 切换到 false,我验证 Creating 是 true,从中调用焦点辅助块,但没有变化)

我还尝试了创建会话变量的跟踪器 - 像这样,无济于事,没有实现焦点:

Tracker.autorun(function () {
  var creating = Session.get('creating');
  console.log('Autorun is auto-running!');
  console.log(creating); 

  if (creating) {
       $('#mainInput').focus(); // I tried documentbyID, etc but nothing
  }
}); 

我意识到它可能与 Tracker 有关,或者可能有一个我不知道的“钩子”(我尝试了渲染模板,但这似乎只在初始创建时有效,有一次)我正在阅读现在指导,但对此仍然很陌生,任何帮助/指导表示赞赏。谢谢!

【问题讨论】:

    标签: jquery meteor


    【解决方案1】:

    您在正确的轨道上,当 Meteor 有机会在 Session 变量无效和空格键 @987654324 后呈现输入时,您只需要使用 Tracker.afterFlush 回调注册来执行 focus 调用@block helper 路径选择。

    Tracker.autorun(function () {
      var creating = Session.get('creating');   
      if (creating) {
        Tracker.afterFlush(function(){
          $('#mainInput').focus();
        });
      }
    });
    

    【讨论】:

    • 像魅力一样工作!流星岩石(你也是)!谢谢。
    【解决方案2】:

    尝试添加自动对焦

    <input name="name" type="text" id="mainInput" autofocus>
    

    【讨论】:

    • 我也试过了!很棒的功能 - 但它只关注初始绘制,而不再关注(在取消/创建之间切换)。
    • 酷,不知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多