gpt4 book ai didi

javascript - 使用 JavaScript 捕获文本框的值

转载 作者:行者123 更新时间:2023-12-02 16:24:02 25 4
gpt4 key购买 nike

我正在尝试显示一个按钮和文本框。让用户输入一个数字。将生成一个随机数,并且用户有 10 次尝试正确回答问题的机会。该脚本应检查用户数量是否等于、小于或大于随机数。我无法获取从文本框中输入的号码。

HTML:

<form name="myForm">
<div id='myForm'></div>
</form>

JavaScript:

   function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);

var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
var check = document.getElementById('textbox').value
button.onclick = calc(guessCount, random, check);

}

function calc(guessCount, random, check){
while(guessCount > 0) {
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;

}
}

最佳答案

您的代码将回调函数结果分配给 onclick 事件而不是函数本身。此外,您还尝试运行一个 while 循环,该循环将消耗第一次单击事件上的guessCount。

我编辑了代码,以下应该可以工作:

   function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
button.onclick = function(){
var check = textbox.value*1;
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;

}

}

关于javascript - 使用 JavaScript 捕获文本框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28864095/

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