我在你的例子假設你要替換a
暫時(你不想更換td
,該表會去搞笑)。
下面是一個簡單的版本:
$("#theTable").delegate("td > a", "click", function(event) {
var a, parent, input, doneLink;
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
// Put the link back, remove our input and other link
a.insertBefore(input);
input.remove();
doneLink.remove();
}
});
Live example
這不是你能做到這一點的唯一方法,但它是相當簡單明瞭。有關詳細信息,請參閱內聯註釋以獲得描述,並請參閱the docs(當然!)。請注意,我們使用閉包來臨時存儲分離的鏈接;關於關閉的更多信息,請參閱Closures are not complicated。
那麼你有什麼嘗試,你有什麼困難?它是讀取單元格值還是創建文本框或用新值替換單元格文本?如果你期望人們花時間幫助你,如果你表明你已經付出了一些努力,你很可能會得到一個很好的答案。 – 2011-03-27 09:48:53