如果有人可以帮助解决这个问题并解释我出错的地方,那将非常感激。我正在尝试编写一个在单击按钮元素时运行的函数。现在,只要第一个提示存储名称变量,它就会立即运行。
HTML:
<body>
<h1>Calculate a right angle:</h1>
<form action="index.html" method="post">
<label for="first">First side:</label>
<input type="text" id="firstSide">
<br><br>
<label for="second">Second side:</label>
<input type="text" id="secondSide">
<br><br>
<label for="long">Long side:</label>
<input type="text" id="longSide">
<br><br>
<button type="button" id="calcBtn">Calculate Triangle</button>
</form>
</body>
使用Javascript:
var firstname = prompt("Please enter your name");
//variables for storing value of each side of triangle
var ss1 = document.getElementById("firstSide").value;
var ss2 = document.getElementById("secondSide").value;
var ls1 = document.getElementById("longSide").value;
document.getElementById("calcBtn").addEventListener("click", calcTriangle(ss1, ss2, ls1));
//creating function for calculating the triangle
function calcTriangle(p1, p2, p3) {
//formula for calculating if triangle is a right angle
var answer = p1 * p1 + p2 * p2;
if (answer == p3 * p3) {
alert("Hi " + firstname + ", this is a right angle.");
} else {
alert("Hi " + firstname + ", this is not a right angle.");
}
}
提前感谢任何能够提供帮助的人。
答案 0 :(得分:0)
你的addEventListener需要该函数的引用,试试这个
.addEventListener("click", calcTriangle)
当你用括号写它时会调用函数
你可以传递你声明的参数
function calcTriangle(ss1, ss2, ls1)
答案 1 :(得分:0)
此示例表示按钮元素中的单击事件处理,并将当前输入元素值传递给您的函数。我还添加了一些基本的验证逻辑来确定是否指定了数值。让我知道它是怎么回事。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script type="text/javascript" language="javascript">
var firstname = prompt("Please enter your name");
if(firstname.trim().length == 0) firstname = "(Unknown)";
//creating function for calculating the triangle
function calcTriangle(p1, p2, p3) {
try
{
if(isNaN(p1) || isNaN(p2) || isNaN(p3) || p1.trim().length==0 || p2.trim().length==0 || p3.trim().length==0)
{
alert("One or more values are not valid numbers!");
return;
}
//formula for calculating if triangle is a right angle
var answer = p1 * p1 + p2 * p2;
if (answer == p3 * p3) {
alert("Hi " + firstname + ", this is a right angle.");
} else {
alert("Hi " + firstname + ", this is not a right angle.");
}
}
catch(e)
{
alert("calcTriangle Error: " + e.Message)
}
}
</script>
</head>
<body>
<h1>Calculate a right angle:</h1>
<form action="index.html" method="post">
<label for="first">First side:</label>
<input type="text" id="firstSide">
<br><br>
<label for="second">Second side:</label>
<input type="text" id="secondSide">
<br><br>
<label for="long">Long side:</label>
<input type="text" id="longSide">
<br><br>
<button type="button" id="calcBtn" onclick="calcTriangle(document.getElementById('firstSide').value, document.getElementById('secondSide').value, document.getElementById('longSide').value)">Calculate Triangle</button>
</form>
</body>
</html>