[英]Trying to create a dog calculate, what am I doing wrong?
So I'm new to JS and trying to create a basic dog calculator to find out dogs age in human years.所以我是 JS 的新手,并试图创建一个基本的狗计算器来找出狗的人类年龄。 1 year for dogs = 7 human years.
狗的 1 年 = 人类的 7 年。
I know I'm close because whenever I run it in console, I get "Your dog is NaN years old in dog years.!".我知道我很接近,因为每当我在控制台中运行它时,我都会得到“你的狗在狗年中是 NaN 岁。!”。
Here's my code:这是我的代码:
Dog Age:<input type="number" id="dogage">
<button onclick="calculateDogAge()"></button>
<h2 id= "humanyears"></h2>
function calculateDogAge(age) {
//1 year for dogs is equivalent to 7 human years
var dogYears= 7 * age;
console.log("Your dog is " + dogYears + " years old in dog years!!");
}
document.getElementById("dogage").innerHTML= humanyears [age];
You dont say where you call your function, but ¡its right..你没有说你在哪里叫你的 function,但它是正确的..
you can return the dogage directly in the function:您可以直接在 function 中返回 dogage:
function calculateDogAge(age) {
//1 year for dogs is equivalent to 7 human years
var dogYears= 7 * age;
return dogYears;
}
You wrote:你写了:
document.getElementById("dogage").innerHTML= humanyears [age];
which makes no sense, what is humanyears?这没有意义,什么是人类年? is it an array?
它是一个数组吗?
To get the input number, you first get the input as an element, and get its value, like this:要获取输入数字,首先将输入作为元素获取,并获取其值,如下所示:
var inputAge=document.getElementById("dogage").value;
and then you call the function:然后调用 function:
var dogAge=calculateDogAge(inputAge);
and finally you write the dog age, maybe in your h2 like this:最后你写了狗的年龄,也许在你的 h2 中是这样的:
document.getElementById("humanyears").innerHTML=dogAge;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.