.getElementById在.createTextNode中返回undefined

时间:2015-03-19 14:46:43

标签: javascript html

我在这里有这个真正简单的代码:

<input type="text" id="haha"></input>
<button onclick="myFunction()">Try it</button>


<script>
    var sth = document.getElementById("haha").value;

    function myFunction() {
        var h = document.createElement("p");
        var t = document.createTextNode("Hello" + sth.value);
        h.appendChild(t);
        document.body.appendChild(h);
    }
</script>

并且一切正常,除了它返回Helloundefined,而不是我输入文本框的值。我也尝试了各种其他的东西,但它会返回任何内容或[object HTMLInputElement]。任何解决方案?

1 个答案:

答案 0 :(得分:1)

您已将sth设置为元素的值:

var sth = document.getElementById("haha").value;

所以sth是一个字符串。然后,您尝试获取该字符串的(不存在的)value属性:

var t = document.createTextNode("Hello" + sth.value);

相反,将sth设置为元素本身:

var sth = document.getElementById("haha");

&#13;
&#13;
var sth = document.getElementById("haha");

function myFunction() {
  var h = document.createElement("p");
  var t = document.createTextNode("Hello " + sth.value);
  h.appendChild(t);
  document.body.appendChild(h);
}
&#13;
<input type="text" id="haha"></input>
<button onclick="myFunction()">Try it</button>
&#13;
&#13;
&#13;