我正在制作一个超级简单的BMI计算器,你可能会说我是Javascript的新手。这是我到目前为止在我的HTML和Javascript文件中所拥有的。我在这里错过了什么来提醒答案?我知道问题出在Javascript的某个地方;我错过了什么。 谢谢。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>BMI Calculator</title>
</head>
<body>
<h1> BMI Calculator</h1>
<form action="" method="get" id="bmi-form">
<div class=section">
<label for="q">Enter Weight in Pounds</label>
<input type="search" id="weight" name="weight" required placeholder="type your weight">
</br>
<label for="h">Enter your Height in Inches</label>
<input type="search" id="height" name="height" required placeholder="type your height">
</div>
<div class="button-group">
<button type="submit" id="btn">Check</button>
</div>
</form>
<div id="output"></div>
<script src="javascript1.js"></script>
</body>
JS:
(function() {
var btn = document.getElementById("btn"),
bmiForm =document.getElementById("bmi-form"),
weight = document.getElementById("weight"),
height = document.getElementById("height");
btn.onclick = function calcBMI() {
var bmi = weight*703/(height*height);
alert('the answer' + bmi);
};
})();
答案 0 :(得分:26)
(请不要将代码发布为图片)
答案 1 :(得分:4)
这里的问题是权重和高度是dom元素引用而不是它们的值,要获得它们需要读取value属性的值
所以
(function() {
var btn = document.getElementById('btn'),
bmiForm = document.getElementById('bmi-form'),
weight = document.getElementById('weight'),
height = document.getElementById('height');
btn.onclick = function(e) {
var bmi = weight.value / (height.value * height.value)
alert(bmi);
//to prevent the form submission
e.preventDefault();
}
})();
<form id="bmi-form">
<input id="weight" />
<input id="height" />
<button type="submit" id="btn">Test</button>
</form>
答案 2 :(得分:0)
bmiForm = document.getElementById("bmi-form").value;
height = document.getElementById("height").value;
weight = document.getElementById("weight").value;
btn.onclick = function(e) {
var bmi = parseInt(weight) / (parseInt(height) * parseInt(height))
e.preventDefault();
alert(bmi);
}