【发布时间】:2012-01-23 13:42:07
【问题描述】:
为了使文本“可编辑”,我编写了一个函数,它将文本替换为输入元素(步骤 1),然后(onchange)将文本替换为输入元素的值(步骤 2)
除了以下情况外,此方法有效:如果输入元素处于活动状态(程序的第 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,例如<th contenteditable>lolwat</th>
标签: javascript input undefined onchange