2013-06-25 78 views
0

所以我已经有了一些帮助,我几乎在那里,但我想知道如果它可能有一个场焦点,当我打进入假设我在特定领域。当按下输入按钮时对焦一个字段

这是我的代码:http://jsfiddle.net/spadez/xT5X5/2/

为了得到它把重点放在“当前”场时,我打在“接受”字段中输入。如果您先添加一些内容,然后点击添加的字段并点击回车,就可以看到这一点。我想这个代码,而无需太多的运气:

$(".accepted").keyup(function(e) { 
    if (e.which == 13) { 
     $(".current").focus(); 
    } 
}); 

另外,我想知道是否有添加这些“输入”命令到我的代码更好的方法,因为它看起来有可能是一个更好的办法。

+0

您显示的代码有什么问题? –

+0

它不起作用:( – Jimmy

+0

.current是一个类名,并且该类有多个字段,如果你想关注一个特定的字段,你可能会给该字段一个唯一的ID并通过id $('# ())。焦点() – daghan

回答

2

更换

$(".accepted").keyup(function(e) { 
    if (e.which == 13) { 
     $(".current").focus(); 
    } 
}); 

有:

$(document).on("keyup",".accepted",function(e) { 
    if (e.which == 13) { 
     $(this).closest('.copies').next().find(".current").focus(); 
    } 
}); 

检查demo

+0

这将始终聚焦相同.current元素 –

+0

是的,谢谢你的作品,但它选择了错误的元素关注于http://jsfiddle.net/spadez/xT5X5/5/ – Jimmy

+0

@roasted:实际上,他需要类似$(this).parent()。find(“。current”)。focus(); –

1

问题是您在页面加载时设置了keyup事件,然后动态创建了文本框 - 结果是文本框没有绑定到任何事件。

所以,你有2个选项添加onClick =“”到文本框的或移动的创建像下面的绑定。

http://jsfiddle.net/xT5X5/4/

  $(html).appendTo(container); 

      $(".accepted").keyup(function(e) { 
       if (e.which == 13) { 
        $(".current").focus(); 
        return false; 
       } 
      }); 
+0

或更好,请使用委托 –

1

您需要更改代码的一部分,你Ç opied这样:

$('.form').on('keyup', '.accepted', function(e) { 
    if (e.which == 13) { 
     var line = $(this).parent(); // this targets '.line' 
     //this targets line's "container", which is '.copy', then find all the .current's in the next node (.line) 
     var current = $(line).parent().next().find('.current'); 

     //as var current returns a list with all the .current's found, even if there's only one, it returns an array of elements in case there were more, so we select the first one from the array 
     current = $(current)[0]; 
     $(current).focus(); 
    } 
}); 

说明: 作为.accepted是文件装载后创建一个类,它不存在,当你绑定KEYUP功能

您需要使用上()来代替,目标'.accepted',

我已经分解了如何找到'.current'你想让你理解它,但你可以通过几种方式实际达到它。我使用了一个我认为会更容易理解的链接,下面是链接到工作小提琴:http://jsfiddle.net/QaHB3/1/

相关问题