流浪漢 - 爲您節省一些時間,在這個答案的底部最後的選擇將最有可能您的首選解決方案
我相信這是你在找什麼:http://jsfiddle.net/2D9FW/
var switchToInput = function() {
var $input = $("<input>", {
val: $(this).text(),
type: "text"
});
$input.addClass("loadNum");
$(this).replaceWith($input);
$input.on("blur", switchToSpan);
$input.select();
};
var switchToSpan = function() {
var $span = $("<span>", {
text: $(this).val()
});
$span.addClass("loadNum");
$(this).replaceWith($span);
$span.on("click", switchToInput);
};
$(".loadNum").on("click", switchToInput);
我的一類,而不是一個ID,所以你可以做多,但你可以切換回來,如果你想要的。如果你想使用ID:http://jsfiddle.net/2D9FW/1/
最近有人調升這使我的注意力又回到了它。這是另一種方式來做到這一點(改變DOM位):http://jsfiddle.net/2khuobze/
<div class="inputSwitch">
First Name: <span>John</span><input />
</div>
<div class="inputSwitch">
Last Name: <span>Doe</span><input />
</div>
JS
$(".inputSwitch span").on("click", function() {
var $this = $(this);
$this.hide().siblings("input").val($this.text()).show();
});
$(".inputSwitch input").on("blur", function() {
var $this = $(this);
$this.hide().siblings("span").text($this.val()).show();
}).hide();
另外,如果你想支持對焦點選擇所有然後按Tab鍵去下一/上跨度/輸入,你可以這樣做(我喜歡這個選項最好):http://jsfiddle.net/x33gz6z9/
var $inputSwitches = $(".inputSwitch"),
$inputs = $inputSwitches.find("input"),
$spans = $inputSwitches.find("span");
$spans.on("click", function() {
var $this = $(this);
$this.hide().siblings("input").show().focus().select();
}).each(function() {
var $this = $(this);
$this.text($this.siblings("input").val());
});
$inputs.on("blur", function() {
var $this = $(this);
$this.hide().siblings("span").text($this.val()).show();
}).on('keydown', function(e) {
if (e.which == 9) {
e.preventDefault();
if (e.shiftKey) {
$(this).blur().parent().prevAll($inputSwitches).first().find($spans).click();
} else {
$(this).blur().parent().nextAll($inputSwitches).first().find($spans).click();
}
}
}).hide();
也有jQuery插件爲 「正在編輯」: http://stackoverflow.com/questions/708801/whats-the-best-edit-in- place-plugin-for-jquery – SailAvid 2013-11-05 15:19:15