我正在尝试制作一个小游戏,你可以在其中输入单词等,但主要问题是当我尝试让 JavaScript 打印出我写的单词时;它永远无法正常工作! 这是我的 HTML:
<input id="verb" name="verb" type="text" placeholder="Enter a verb">
<input id="noun" name="noun" type="text" placeholder="Enter a noun">
<button onclick="getWords()">Enter</button>
<p id="output"></p>
这是与之配套的 JavaScript:
var verb = document.getElementById("verb").textContent;
var noun = document.getElementById("noun").textContent;
function getWords()
{
document.getElementById("output").textContent = "You chose " +verb+ " as your verb, and " +noun+ " as your noun";
}
当您在 Google Chrome 中单击输入按钮时;它只是说“你选择了 undefined 作为你的动词,并且 undefined 作为你的名词。”
为什么它不能识别元素的内容,而无论输入什么内容,都只用“未定义”填充它们?有没有更简单的方法来做到这一点?提前致谢!
最佳答案
尝试
function getWords()
{
var verb = document.getElementById("verb").value;
var noun = document.getElementById("noun").value;
document.getElementById("output").innerHTML = "You chose " +verb+ " as your verb, and " +noun+ " as your noun";
}
value 保存输入中的文本,而innerHTML 表示元素中的HTML。因此,您需要读取输入的值并将它们存储在段落元素的 HTML 中。
关于javascript - 使用 JavaScript 获取文本内容并写入 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25004467/