帮助聚焦动态创建的输入

我的代码就是这个。 在jsfiddle 。

var inp = $('').attr({'class':'txtEdit txt', 'type':'text'}) .val($(this).html()).blur(function (){ if($(this).val().length != ''){ $(txt).replaceWith($(editable) .html($(this).val())); } else{ alert("Cannot contain empty value!")} }).keydown(function (e){ if(e.keyCode == 13 || e.keyCode == 9){ e.preventDefault(); $(this).trigger('blur'); } }).appendTo($(txt)); 

我正在创建一个包含大量事件的输入元素并添加到div。 现在我想关注它,因为它被附加到DOM。 但重点似乎并没有奏效。

这是总代码。

   My jQuery plugin   $(function () { $('.editable').txtEdit(); }); (function($){ $.fn.txtEdit = function() { var editable = $(this); $(editable).live('click', function () { var txt = $('
').attr('class', 'txtEdit div'); var inp = $('').attr({'class':'txtEdit txt', 'type':'text'}) .val($(this).html()).blur(function (){ if($(this).val().length != ''){ $(txt).replaceWith($(editable) .html($(this).val())); } else{ alert("Cannot contain empty value!")} }).keydown(function (e){ if(e.keyCode == 13 || e.keyCode == 9){ e.preventDefault(); $(this).trigger('blur'); } }).appendTo($(txt)); $(this).replaceWith(txt); } ); }; })(jQuery);
this is editable div

任何想法?

问候,

 inp.focus(); 

 $(this).replaceWith(txt); 

因为你的div是在焦点动作之后创建的,这是错误的。 您应该显示div然后专注于输入。

创建输入框后,不要链接焦点,而是添加它。

 inp.focus(); 

做就是了

 inp.focus(); 

$(this).replaceWith(txt);

你正在做的是在将元素添加到DOM之前尝试聚焦元素( 当它仍在内存中时 )。

住在http://jsfiddle.net/gaby/KH7pZ/8/

你需要放

 inp.focus(); 

代码结束时(更换完成后);

这是你最新的小提琴: http : //jsfiddle.net/KH7pZ/9/