【问题标题】:Javascript onchange - get undefined on clickJavascript onchange - 点击时未定义
【发布时间】: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,例如&lt;th contenteditable&gt;lolwat&lt;/th&gt;

标签: javascript input undefined onchange


【解决方案1】:

1\ 第一次单击

元素时,它的第一个子节点是一个文本节点。它的数据属性是“2.文本”。所以当你引用 this.firstChild 时,它是一个文本节点。

2\函数changeText会以文本节点为参数调用,所以“实际”将是一个文本节点。

然后将文本节点更改为文本框。

3\ 当你点击文本框时,它的父级的onclick处理程序再次被执行(

的onclick),但是这一次,this.firstChild是一个标签,所以函数会被调用以输入元素作为参数。参数“实际”将是一个输入元素。 输入元素没有称为数据的属性,所以在这一行
    textfield.setAttribute("value", actual.data);

actual.data 未定义。

这就是你问题的答案,但我想澄清一些事情:

您实际上可以使用 textfield.onclick = function () { ..... } 编写一个更安全的方法。

使用 onchange 将文本框改回文本并不总是很舒服(例如,如果您不想更改任何内容),您应该检查元素是否也失去焦点(模糊)。

【讨论】:

  • 哦,我想你误解了我的问题;我会编辑它,所以它更清晰
  • 好的,我已经写了一个简短的演练。
  • 啊我忘了冒泡了;所以检查 actual.data 就可以了;非常感谢
  • 这里没有冒泡:D,它是同一个处理程序用不同的参数调用了两次。不相关但也检查一下:html5demos.com/contenteditable
  • 感谢添加,但这些步骤受我的其他软件的影响;这只是一个发现我的问题的例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 2012-09-19
  • 2021-02-15
  • 2023-04-05
相关资源
最近更新 更多