[英]How can I access form input from an input field which was created dynamically via a Javascript function?
I'm new to programming and hope you can help me out with this little number comparison game that I'm trying to build.我是编程新手,希望您能帮助我解决这个我正在尝试构建的小型数字比较游戏。
I have two functions.我有两个功能。 The first function creates the playing field in HTML via a button press.第一个 function 通过按下按钮在 HTML 中创建了运动场。 One of the elements created on the playing field is an input field where the player can enter their guess.在运动场上创建的元素之一是输入字段,玩家可以在其中输入他们的猜测。 In the second function I compare two numbers - the one that was generated randomly and the one that was input by the player.在第二个 function 中,我比较了两个数字——一个是随机生成的,另一个是玩家输入的。 Unfortunately I can't access the number which was entered by the player.不幸的是,我无法访问玩家输入的号码。
Maybe someone has got an idea.也许有人有了主意。 Thank you very much.非常感谢你。
This is what the functions look like:这就是函数的样子:
function startGame(){
(...)
const inputField = document.createElement("input");
inputField.setAttribute("type", "number");
inputField.setAttribute("id", "guess");
document.getElementById("guess").appendChild(inputField);
}
function compareInput(){
let inputValue = document.getElementById("guess").value;
(...)
}
I implemented a proof-of-concept, which probably differs from your requirements, but it should help you finding the right path.我实施了一个概念验证,它可能与您的要求不同,但它应该可以帮助您找到正确的路径。 First, let's make sure that the new field has a value.首先,让我们确保新字段具有值。 Next, make sure that we append it to document
rather than itself.接下来,确保我们 append 是它来document
而不是它本身。
function startGame(){ const inputField = document.createElement("input"); inputField.setAttribute("type", "number"); inputField.setAttribute("id", "guess"); inputField.value = parseInt(Math.random() * 10) + 1; document.body.appendChild(inputField); } function compareInput(){ let inputValue = document.getElementById("guess").value; console.log(inputValue); } startGame(); compareInput();
You're trying to append "guess" to itself.您正在尝试 append 自己“猜测”。 That doesn't work like that.那不是那样的。 Try to append it to another div or body.尝试将它 append 到另一个 div 或 body。
You have two elements with the same ID.您有两个具有相同 ID 的元素。 The first is the wrapper and the second is the input.第一个是包装器,第二个是输入。 Hence ur function compareInput()
is trying to get the value of the wrapper.因此,您的 function compareInput()
正在尝试获取包装器的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.