爲了使文本「可編輯」,我寫了一個函數,它用輸入元素(step1)替換文本,後來(onchange)用輸入值替換文本-lelement(step2)Javascript onchange - 點擊未定義
這有效,除了以下情況:如果輸入元素處於活動狀態(程序的第1步),並且在輸入元素中單擊,則(在輸入元素中)文本被替換爲「不確定」,功能不能正常工作更多的
<html>
<head>
<title>Test</title>
<script type="text/javascript">
<!--
// global variables for use in (out-of-function) listeners
var changeText_actual;
var changeText_parent;
function changeText(actual) {
// element representing a textNode
changeText_actual = actual;
// element containing the textNode
changeText_parent = actual.parentNode;
// create a new html-element to input text
var textfield = window.document.createElement("input"); {
textfield.setAttribute("type", "text");
// text in textNode
textfield.setAttribute("value", actual.data);
// listener for when user has finished input (e.g. by pressing return)
textfield.setAttribute("onchange",
// if inputText is not empty
"if(this.value && this.value.length > 0) {"
// fill textNode with inputText
+" changeText_actual.data = this.value;"
+"}"
// remove input-element and put textNode inplace
+"changeText_parent.replaceChild(changeText_actual, this);"
);
}
// remove textNode and put input-element inplace
changeText_parent.replaceChild(textfield, changeText_actual);
// select inputText for faster editing
textfield.select();
}
//-->
</script>
</head>
<body>
<table border="1"><tr>
<th>1. Text</th><th onclick="changeText(this.firstChild)">2. Text</th><th>3. Text</th>
</tr><tr>
<td>4. Text</td><td>5. Text</td><td>6. Text</td>
</tr></table>
</body>
</html>
我只是尋求比解決一個解釋,因爲我覺得能夠解決此問題的工作,如果我知道,「未定義」來自哪裏(並且我可以捕捉到它)
只需使用'contentEditable',例如'