我的代码是这样的。在jsfiddle http://jsfiddle.net/KH7pZ/1/.
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 时将其聚焦。但焦点似乎不起作用。
这是总代码。
<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>
有人有什么想法吗?
Regards,
add
inp.focus();
after
$(this).replaceWith(txt);
因为你的 div 是在焦点操作之后创建的,这是错误的。
您应该显示 div,然后专注于输入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)