gpt4 book ai didi

javascript - 我需要使用 jQuery 函数来检查数字范围并查看它是否经过验证并且它不起作用

转载 作者:行者123 更新时间:2023-11-28 10:50:16 24 4
gpt4 key购买 nike

我刚刚开始学习如何使用 jQuery 我需要验证输入字段并测试输入的数字范围。我已经写了我认为正确的方法,但它不起作用,事实上,如果你输入范围内的数字,游戏中不会发生任何事情。如果输入的数字不在范围内,我还想让输入框变成“红色”,如果不合适,我还想把我包含在我的代码中的输出消息。

这是我的代码:

<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js">
</script>
<link rel="stylesheet" type="text/css" href="dice.css">
<title>Dice Game</title>
</head>

<body>
<script type="text/javascript">
$(document).ready(function () {
$('#guess').focus();
$('#roll').click(function () {});

$("#guess").validate({
rules: {
guess: {
required: true,
range: [2, 12]
}
}, //end of rules

message: {

guess: {
required: "Please enter a number.",
range: "You must enter a number between 2 and 12."
}
}
}); //end of validate()

var count = 3;

function startover() {
count = 3;
alert("Make a guess and click the Roll button.");
}

function roll(guess) {

if (count == 0) {
alert("Click the Play Again button.");
return;
}

var die1 = Math.floor(1 + 6 * Math.random());
var die2 = Math.floor(1 + 6 * Math.random());

var sum = die1 + die2;

if (guess == sum) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". Congratulations, you win!");
count = 0;
} else {
--count;
if (count == 0) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have no rolls left. " +
"Sorry... the computer won.");
} else {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have " + count + " rolls left. " +
"Click Roll to try again.");
}
}
}
}); // end ready </script>
<form id="game">
<h1>Welcome to the dice game!</h1>
<p>Here's how it works! If you roll two dice and add up the values, you will get a minimum of 2 and a maximum of 12.</p>
<p>Enter a number between 2 and 12:
<input type="text" name="guess" id="guess" min="2" max="12" />
<br>The computer will roll the dice for you up to three times. If the dice match your guess, you win!</p>
<input type="button" value="Roll" onclick="roll(guess.value);" />
<input type="button" value="Play Again" onclick="startover();" />
</p>
</form>
</body>

</html>

最佳答案

您的代码存在以下问题:

  1. 按钮事件处理程序的 javascript 函数不应放在 $(document).ready(); 内

  2. jQuery 验证插件应该在您的表单元素 ($("#game").validate 上运行,而不是在您的输入文本元素上运行 ($("#guess").validate)。

  3. 为了突出显示无效输入,您需要添加“错误”和“有效”css 样式。

  4. 为了停止游戏继续进行,您可以在表单验证失败时禁用提交按钮,使用:

    onkeyup:函数(元素,事件){
    如果(!$(“#game”)。有效()){
    $(":button").attr("已禁用", "已禁用");
    } 别的 {
    $(":button").removeAttr("已禁用", "已禁用");
    }
    }

请参阅Plunker有工作代码。

注意:我没有看你的游戏逻辑,也没有修改它,我已经修复了验证部分。

关于javascript - 我需要使用 jQuery 函数来检查数字范围并查看它是否经过验证并且它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22824252/

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