gpt4 book ai didi

javascript - .getElementById 在 .createTextNode 中返回未定义

转载 作者:行者123 更新时间:2023-12-03 10:32:26 25 4
gpt4 key购买 nike

我在这里得到了这个真正简单的代码:

<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] 。有什么解决办法吗?

最佳答案

您正在将 sth 设置为元素的值:

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

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

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

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

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

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);
}
<input type="text" id="haha"></input>
<button onclick="myFunction()">Try it</button>

关于javascript - .getElementById 在 .createTextNode 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com