帮助集中动态创建的输入 [英] help with focusing a dynamically created input
本文介绍了帮助集中动态创建的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码是这个.在 jsfiddle 上.
my code is this. on jsfiddle.
var inp = $('<input>').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上.但是焦点似乎没有用.
I am creating an input element with lots of events and adding to div. Now i want to focus it as it is appended to DOM. but focus does not seem to be working.
这是总代码.
<html>
<head>
<title>My jQuery plugin</title>
<script src="jquery.js"></script>
<script>
$(function ()
{
$('.editable').txtEdit();
});
(function($){
$.fn.txtEdit = function() {
var editable = $(this);
$(editable).live('click',
function ()
{
var txt = $('<div>').attr('class', 'txtEdit div');
var inp = $('<input>').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);
</script>
</head>
<body>
<div class="editable">this is editable div</div>
</body>
</html>
任何想法吗?
此致
推荐答案
添加
inp.focus();
之后
$(this).replaceWith(txt);
因为您的div是在焦点操作之后创建的,所以这是错误的. 您应该显示div,然后专注于输入.
Because your div is created after focus action, which is wrong. You should display the div and then focus on input.
这篇关于帮助集中动态创建的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文