使用 JS 显示 HTML 计算输出
Using JS to show HTML output of calculation
我正在尝试使用 HTML 和 JS 构建一个卡路里计算器,目前正在努力在屏幕上显示输出(或通过 console.log)。我知道我在做一些非常基本的错误,但目前无法确定那是什么。
下面是我的 HTML 和 JS 代码:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
function calcBMR(gender, weightKG, heightCM, age) {
// Calculate BMR
if (gender = 'male') {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
试试这个,你几乎完成了,只需在用户单击按钮时从输入中获取值。
但我必须注意到 submit
按钮会立即重定向到一个新页面,如果你想显示结果,你应该使用 click
代替。
document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
let weight = document.querySelector('#weight').value
let height = document.querySelector('#height').value
let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
function calcBMR(gender, weightKG, heightCM, age) {
let BMR
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
document.querySelector('#output').textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
首先,您正在使用带有 type="submit"
的按钮,该按钮用于将表单数据提交到将接收并处理它的资源。在这种情况下,您可能只需要一个带有 type="button"
的按钮,它只会执行您配置它执行的操作(在屏幕上显示结果)。
进行更改后,您应该用结果填充 pre-existing,但为空元素。
但是您确实对声明的方式和位置有疑问 BMR
。 let
声明应该在 if/then
代码之外但在函数内部,因此它在整个函数中都有范围。
此外,您的按钮 ID 在事件处理程序设置中不正确。
接下来,您从 HTML 元素获得的任何值都将是一个字符串,如果您打算对该值进行数学运算,则需要将其转换为 JavaScript 数字.有几种方法可以做到这一点,但一种 shorthand 方法是在值前面加上 +
,正如您将在下面看到的那样。
此外,如果有人在性别文本框中输入 Male
,您的代码将不会将其处理为男性,因为您的代码只检查 male
,而不检查 Male
。通过强制输入小写,您的代码将起作用(前提是它们拼写正确)。最好使用一组单选按钮或下拉列表供用户选择。
并且,与此相结合,JavaScript 使用 =
来赋值,而不是比较。对于松散相等(自动类型转换)使用 ==
,对于严格相等(无类型转换),使用 ===
.
let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");
// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
function calcBMR(gender, weightKG, heightCM, age) {
let BMR = null; // Declare the variable in the function scope
console.log(gender, weightKG, heightCM, age);
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="button" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
您可以删除行 document.getElementById("bmrForm").addEventListener("submit", calcBMR);
您可以将事件传递给 onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">
function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
为了达到您想要的结果,需要修改几项内容。
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
行是不需要的,因为我们可以直接将函数传递给 form
元素的 onsubmit
属性。
gender
、weightKG
、heightCM
和 age
参数不会自动传递给 calcBMR
函数。需要从文档中检索值。
BMR
变量需要在 if/else 块上方定义,因为 scoping.
- 需要在
onsubmit
属性中加入return
语句,使表单不提交,不刷新页面。或者,如果所需的效果是更新屏幕上的文本,添加了 click
事件处理程序的 button
元素可能比添加 form
的 [=] 元素更好。 26=]处理程序。
- 在 JavaScript 中使用
==
或 ===
比较字符串。因此需要将gender = 'male'
部分改为gender === 'male'
.
- 为了更新输出,可以将元素的
textContent
更改为 document.getElementById("output").textContent = BMR
。
下面是包含上面所列更改的代码。
function calcBMR() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let BMR;
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
document.getElementById("output").textContent = BMR;
return false;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="return calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
BMR
在 if
树中,它必须在父树中。
试试这个!
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.getElementById('output');
function calcBMR(event) {
// Get the [gender, weightKG, heightCM, age] value
let gender = document.getElementById('gender').value;
let weightKG = document.getElementById('weight').value;
let heightCM = document.getElementById('height').value;
let age = document.getElementById('age').value;
// Set default BMR to 0
let BMR = 0;
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.innerText = BMR;
// Cancel form submit
event.preventDefault();
return;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
我使用选择器而不是性别文本字段。
我使用 form.elements
从表单中获取值。
我使用 event.preventDefault();
来防止表单在提交时重定向。
// your form
var form = document.getElementById("formId");
var DoMagic = function(event)
{
event.preventDefault();
var elements = form.elements;
if (elements["gender"].value == "male")
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
}
else
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
}
document.getElementById("result").textContent = "Result: " + result;
}
// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
<label>Gender</label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label>Weight (kg)</label>
<input name="weight" type="number">
<br>
<label>Height (cm)</label>
<input name="height" type="number">
<br>
<label>Age (years)</label>
<input name="age" type="number">
<br>
<input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>
工作Codepen
您的代码中存在一些根本性缺陷。话虽如此,学习这个确实可以让你正确理解Javascript。
HTML:
<body>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?" name="gender">
<input type="number" id="weight" placeholder="Weight in KG" name="weight">
<input type="number" id="height" placeholder="Height in CM" name="height">
<input type="number" id="age" placeholder="How old are you?" name="age">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Javascript:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
function calcBMR(e) {
e.preventDefault();
output.innerText = ''
const formData = new FormData(e.target)
const { age, gender, height, weight} = Object.fromEntries(formData);
let BMR = 0
// Calculate BMR
if (gender === 'male') {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
} else {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
}
output.innerText = BMR
}
我正在尝试使用 HTML 和 JS 构建一个卡路里计算器,目前正在努力在屏幕上显示输出(或通过 console.log)。我知道我在做一些非常基本的错误,但目前无法确定那是什么。
下面是我的 HTML 和 JS 代码:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
function calcBMR(gender, weightKG, heightCM, age) {
// Calculate BMR
if (gender = 'male') {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
试试这个,你几乎完成了,只需在用户单击按钮时从输入中获取值。
但我必须注意到 submit
按钮会立即重定向到一个新页面,如果你想显示结果,你应该使用 click
代替。
document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
let weight = document.querySelector('#weight').value
let height = document.querySelector('#height').value
let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
function calcBMR(gender, weightKG, heightCM, age) {
let BMR
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
document.querySelector('#output').textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
首先,您正在使用带有 type="submit"
的按钮,该按钮用于将表单数据提交到将接收并处理它的资源。在这种情况下,您可能只需要一个带有 type="button"
的按钮,它只会执行您配置它执行的操作(在屏幕上显示结果)。
进行更改后,您应该用结果填充 pre-existing,但为空元素。
但是您确实对声明的方式和位置有疑问 BMR
。 let
声明应该在 if/then
代码之外但在函数内部,因此它在整个函数中都有范围。
此外,您的按钮 ID 在事件处理程序设置中不正确。
接下来,您从 HTML 元素获得的任何值都将是一个字符串,如果您打算对该值进行数学运算,则需要将其转换为 JavaScript 数字.有几种方法可以做到这一点,但一种 shorthand 方法是在值前面加上 +
,正如您将在下面看到的那样。
此外,如果有人在性别文本框中输入 Male
,您的代码将不会将其处理为男性,因为您的代码只检查 male
,而不检查 Male
。通过强制输入小写,您的代码将起作用(前提是它们拼写正确)。最好使用一组单选按钮或下拉列表供用户选择。
并且,与此相结合,JavaScript 使用 =
来赋值,而不是比较。对于松散相等(自动类型转换)使用 ==
,对于严格相等(无类型转换),使用 ===
.
let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");
// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
function calcBMR(gender, weightKG, heightCM, age) {
let BMR = null; // Declare the variable in the function scope
console.log(gender, weightKG, heightCM, age);
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="button" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
您可以删除行 document.getElementById("bmrForm").addEventListener("submit", calcBMR);
您可以将事件传递给 onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">
function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
为了达到您想要的结果,需要修改几项内容。
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
行是不需要的,因为我们可以直接将函数传递给form
元素的onsubmit
属性。gender
、weightKG
、heightCM
和age
参数不会自动传递给calcBMR
函数。需要从文档中检索值。BMR
变量需要在 if/else 块上方定义,因为 scoping.- 需要在
onsubmit
属性中加入return
语句,使表单不提交,不刷新页面。或者,如果所需的效果是更新屏幕上的文本,添加了click
事件处理程序的button
元素可能比添加form
的 [=] 元素更好。 26=]处理程序。 - 在 JavaScript 中使用
==
或===
比较字符串。因此需要将gender = 'male'
部分改为gender === 'male'
. - 为了更新输出,可以将元素的
textContent
更改为document.getElementById("output").textContent = BMR
。
下面是包含上面所列更改的代码。
function calcBMR() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let BMR;
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
document.getElementById("output").textContent = BMR;
return false;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="return calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
BMR
在 if
树中,它必须在父树中。
试试这个!
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.getElementById('output');
function calcBMR(event) {
// Get the [gender, weightKG, heightCM, age] value
let gender = document.getElementById('gender').value;
let weightKG = document.getElementById('weight').value;
let heightCM = document.getElementById('height').value;
let age = document.getElementById('age').value;
// Set default BMR to 0
let BMR = 0;
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.innerText = BMR;
// Cancel form submit
event.preventDefault();
return;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
我使用选择器而不是性别文本字段。
我使用 form.elements
从表单中获取值。
我使用 event.preventDefault();
来防止表单在提交时重定向。
// your form
var form = document.getElementById("formId");
var DoMagic = function(event)
{
event.preventDefault();
var elements = form.elements;
if (elements["gender"].value == "male")
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
}
else
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
}
document.getElementById("result").textContent = "Result: " + result;
}
// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
<label>Gender</label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label>Weight (kg)</label>
<input name="weight" type="number">
<br>
<label>Height (cm)</label>
<input name="height" type="number">
<br>
<label>Age (years)</label>
<input name="age" type="number">
<br>
<input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>
工作Codepen
您的代码中存在一些根本性缺陷。话虽如此,学习这个确实可以让你正确理解Javascript。
HTML:
<body>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?" name="gender">
<input type="number" id="weight" placeholder="Weight in KG" name="weight">
<input type="number" id="height" placeholder="Height in CM" name="height">
<input type="number" id="age" placeholder="How old are you?" name="age">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Javascript:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
function calcBMR(e) {
e.preventDefault();
output.innerText = ''
const formData = new FormData(e.target)
const { age, gender, height, weight} = Object.fromEntries(formData);
let BMR = 0
// Calculate BMR
if (gender === 'male') {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
} else {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
}
output.innerText = BMR
}