如何从Meteor事件处理程序中聚焦DOM子元素 [英] How to focus a DOM child element from a Meteor event handler

查看:82
本文介绍了如何从Meteor事件处理程序中聚焦DOM子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件处理程序设置一个会话变量来更改DOM元素中的内容 - 在这种情况下是一个表单元格。

I have an event handler that sets a session variable to change the content within a DOM element -- in this case a table cell.

'dblclick td.itemName': function (evt) {
  Session.set("editItemName",true);
  evt.currentTarget.children[0].focus();
},


                <td class="itemName">
                {{#unless editItemName}}
                    {{name}} 
                {{else}}
                    <input class="editItemName" type="text" value="{{name}}" style="width:100px;">
                {{/unless}}
                </td>

很直接...

然而evt.currentTarget.children不工作。一旦输入了文本,我想让它自动聚焦...流星文件说这是一个DOM对象,所以它的奇怪的孩子的功能不工作...

However evt.currentTarget.children doesnt work. Once the input takes place of the text, I'd like to make it automatically focus... The meteor docs say that this is a DOM object so its weird that the children function doesnt work...

谢谢

Chet

推荐答案

当您双击并且您的函数运行时,将会话 editItemName 设置为true,然后尝试给出输入元素焦点,但模板没有已被重新渲染,所以没有创建输入元素(模板将在你的函数返回一段时间后重新渲染)。换句话说: evt.currentTarget.children [0] 不是对input-element的引用。

When you double click, and your function runs, you set the session editItemName to true, and then you're trying to give the input-element focus, but the template has not been re-rendered yet, so the input-element hasn't been created (the template will be re-rendered some time after your function returns). In other words: evt.currentTarget.children[0] is not a reference to the input-element.

可能的解决方案1 ​​

在HTML 5中有一个名为autofocus的属性,您可以使用它(至少可以在Chrome中)。只需将它添加到input元素中:

In HTML 5 there's an attribute called autofocus, which you can use (at least I can in Chrome). Just add it to the input-element:

<input autofocus="autofocus" class="editItemName" type="text" value="{{name}}" style="width:100px;">

可能的解决方案2

否则,当渲染模板并且您的输入元素存在时,您必须将其集中在JavaScript中:

Otherwise you have to focus it with JavaScript when the template been rendered and your input-element exists in it:

Template.yourTemplate.rendered = function(){

    var input = this.find('.editItemName')

    if(input){
        input.focus()
    }

}

这篇关于如何从Meteor事件处理程序中聚焦DOM子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆