![](/img/trans.png)
[英]My javascript function doesn't seem to be working. I can't figure out why
[英]I can't figure out my JavaScript function is not working
我必须创建一个游戏,用户必须在其中猜测一个数字,为此我在单击按钮时激活的外部文件上调用 JavaScript 函数。
我的 HTML :
`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Devoir JavaScript</title>
</head>
<body>
<p>Vous devez trouver un nombre compris entre 1 et 100 !</p>
<form name="myForm" method="POST"></form>
Nombre : <input type="text" name="nombre" value="" />
<input type="button" onclick="return verif()" value="Jouer" />
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
`我的 JavaScript :
var numero = Math.floor(Math.random() * 100) + 1;
var essai = 0;
function verif() {
essai++;
var choix = document.forms["myForm"]["choix"].value;
if (choix == null || choix == "") {
alert("Indiquer un nombre !");
return false;
}
if (choix < numero) {
alert = "Le nombre indiquer est trop petit !";
return false;
}
if (choix > numero) {
alert = "Le nombre indiquer est trop grand !";
return false;
}
if (choix == numero) {
alert = "Bravo vous avez trouver en " + essai + "essais !";
return true;
}
}
我已经检查了我的文件的名称及其扩展名,以免出错。 我不明白或我犯了一个错误。 PS:我是 JavaScript 新手。 我从昨天开始一直在找,所以谢谢你的帮助。
我尝试运行您的代码,在 Console 中它说无法读取该值。 我稍微更改了您的 Javascript 代码并且它起作用了。
//var choix = document.forms["myForm"]["choix"].value; code before
var choix = document.getElementsByName("nombre").value; //after changed
如果您的代码没有运行,则在使用 Javascript 时,您应该按 F12 并查看控制台以查看您的代码失败的地方。
这是我更改的完整代码:
var numero = Math.floor(Math.random() * 100) + 1; var essai = 0; function verif() { essai++; var choix = document.getElementsByName("choix").value; document.write(choix); if (choix == null || choix == "") { alert("Indiquer un nombre !"); return false; } if (choix < numero) { alert = "Le nombre indiquer est trop petit !"; return false; } if (choix > numero) { alert = "Le nombre indiquer est trop grand !"; return false; } if (choix == numero) { alert = "Bravo vous avez trouver en " + essai + "essais !"; return true; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Devoir JavaScript</title> </head> <body> <p>Vous devez trouver un nombre compris entre 1 et 100 !</p> <form name="myForm" method="POST"></form> Nombre : <input type="number" name="choix" value=""/> <input type="button" onclick="return verif()" value="Jouer" /> </form> </body> </html>
您的错误表明您正在从undefined
访问属性value
。 您的 HTML 中没有“choix”。
您可以使用索引来获取您的特定元素值:
var choix = document.forms[0].elements[0].value;
或者保持与您相同的方法,我可以使用正确的字段 "nombre" :
var choix = document.forms["myForm"]["nombre"].value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.