我正在尝试制作一个javascript程序,当你给它输入时解决了毕达哥拉斯定理。但由于某种原因,它不起作用。这是代码:`
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
function myFunction() {
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>
答案 0 :(得分:2)
首先,您需要移动函数内部的数据收集。否则你将永远不会有输入值。
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
function myFunction() {
//moved two lines below so they are inside the function declaration.
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>
答案 1 :(得分:0)
只需将脚本部分替换为以下部分:
<script>
function myFunction() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
您所要做的就是移动getElementById行以确认函数:)