我试图在使用功能的span和输入文本字段之间切换,但我需要一些帮助来找出我做错了什么。
我在这里创建了一个小提琴
UI<div>
<span >My value here!</span>
</div>
JS
var focusInName = '';
var focusOutName = '';
$(function () {
$("document").on("click",".span", function () {
var input = $('<input />', {'type': 'text', 'name': 'aname', 'value': $(this).html()});
$(this).parent().append(input);
$(this).remove();
input.focus();
focusInName = $(this).html();
alert(focusInName);
});
$('document').on('blur',".input", function () {
$(this).parent().append($('<span />').html($(this).val()));
$(this).remove();
focusOutName = $(this).val();
alert(focusOutName);
});
});
你应该把jquery的版本改为1.9然后将class更改为html元素,如下所示:
$(document).on("click","span", function () {
//codes
}
输入字段也一样:
$(document).on('blur',"input", function () {
//codes
}
编辑
如果你想把类设置为html元素,你可以这样做:
var focusInName = '';
var focusOutName = '';
$(function () {
$(document).on("click",".sp", function () {
var input = $('<input class="box" />', {'type': 'text', 'name': 'aname','value': $(this).html()});
$(this).parent().append(input);
$(this).remove();
input.focus();
focusInName = $(this).html();
alert(focusInName);
});
$(document).on('blur',".box", function () {
$(this).parent().append($('<span class="sp" />').html($(this).val()));
$(this).remove();
focusOutName = $(this).val();
alert(focusOutName);
});
});
演示我建议您使用简单的contenteditable
<span contentEditable="true">My value here!</span>
你需要使用jQuery 1.7+作为$.fn.on()
,因为它是在1.7
HTML,首先添加所需的类,即span
到元素
<span class='span'>My value here!</span>
代码:
var focusInName = '';
var focusOutName = '';
$(function () {
$(document).on("click", ".span", function () {
focusInName = $(this).html();
var input = $('<input />', {
'type': 'text',
'name': 'aname',
'value': $(this).html(),
'class': 'input' //Add the CSS class while creating element
});
input.focus();
$(this).parent().append(input);
$(this).remove(); //Always remove at the end
alert(focusInName);
});
$(document).on('blur', ".input", function () {
focusOutName = $(this).val();
var span = $(
'<span />', {
'class': 'span', //Add the CSS class while creating element
'html': $(this).val()
});
$(this).parent().append(span);
$(this).remove(); //Always remove at the end
alert(focusOutName);
});
});
修改后的小提琴