javascript未读取输入框中的输入值

javascript not reading entered value in input box

本文关键字:输入 读取 javascript      更新时间:2023-09-26

我无法获得函数AreaT((来验证和验证输入框中输入的值作为三角形区域的答案。即使是正确的答案,我也总是收到"错误"的信息。我做错了什么?谢谢你花时间检查我的代码。

<html>
<head>
<script>
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
var area = getElementById("area");
 function AreaT(){
 document.getElementById('height').value = height;
    document.getElementById('base').value = base;
if(area== 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
</script>
  </head>
  <body>
 <form>
<h2>HEIGHT:</h2><input  type="button" size="20" id="height"/>
<h2>BASE: </h2><input  type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input  type="text" size="20"  id="area"/>
 <input  type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</form>

</body>

</html>

试试这个:

HTML

<body>
<h2>HEIGHT:</h2><input  type="button" size="20" id="height"/>
<h2>BASE: </h2><input  type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input  type="number" size="20"  id="area"/>
<input  type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</body>

Javascript(放在<header>标签中(

var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
document.getElementById('height').value = height;
document.getElementById('base').value = base;

 function AreaT(){
var area = document.getElementById("area").value;
if(area == 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}

在前面已经提到的基础上,还需要向面积元素添加一个.value。我还将AREA的输入类型更改为number

getElementById("area")更改为document.getElementById("area").value。您还需要从AreaT()函数内部分配area,否则它将无法获得用户键入的值。

此外,您的javascript需要位于这些表单元素下方,否则它无法"看到"它们,您将获得未定义的值。