gpt4 book ai didi

javascript - 更新输入数字变量 onclick

转载 作者:行者123 更新时间:2023-11-30 10:02:15 26 4
gpt4 key购买 nike

我正在尝试创建一个 calculator 样式的东西,您可以在其中输入多少年,然后点击提交,它会在下面给出不同的结果,而无需重新加载页面。

我现在可以进行所有计算,但我无法在单击提交按钮时更新输入数字变量,然后在页面上打印正确的结果。我已经在谷歌上搜索了一个小时,但我似乎无法找到正确的答案,我仍在学习 JS。

这是我的JS:

// Get Years
var years = (document.getElementById('years').value);
// Variables
var years;
var gallons = 1100 * 365;
var grain = 45 * 365;
var forest = 30 * 365;
var co2 = 20 * 365;
var animal = 1 * 365;
// Calculations
var gallonsTotal = years * gallons;
var grainTotal = years * grain;
var forestTotal = years * forest;
var co2Total = years * co2;
var animalTotal = years * animal;
// Functions
function calc() {
var years = (document.getElementById('years').value);
//Prints
document.querySelector('.gallons').innerHTML = "Gallons " + gallonsTotal;
document.querySelector('.grain').innerHTML = "Gains " + grainTotal;
document.querySelector('.forest').innerHTML = "Forest " + forestTotal;
document.querySelector('.co2').innerHTML = "Co2 " + co2Total;
document.querySelector('.animals').innerHTML = "Animals " + animalTotal;
};

HTML:

<div class="small-4 columns">
<input type="number" id="years" min="1" max="99">
</div>
<div class="small-8 columns">
<a href="#" class="button postfix submit" onclick="calc()">Submit</a>
</div>

这是我目前进展的笔迹:http://codepen.io/LukeD1uk/pen/BNwXMX

最佳答案

你需要把所有的计算都放到calc()函数中:

function calc() {
// Get Years
var years = (document.getElementById('years').value);
// Variables
var years;
var gallons = 1100 * 365;
var grain = 45 * 365;
var forest = 30 * 365;
var co2 = 20 * 365;
var animal = 1 * 365;
// Calculations
var gallonsTotal = years * gallons;
var grainTotal = years * grain;
var forestTotal = years * forest;
var co2Total = years * co2;
var animalTotal = years * animal;
// Functions

var years = (document.getElementById('years').value);
//Prints
document.querySelector('.gallons').innerHTML = "Gallons " + gallonsTotal;
document.querySelector('.grain').innerHTML = "Gains " + grainTotal;
document.querySelector('.forest').innerHTML = "Forest " + forestTotal;
document.querySelector('.co2').innerHTML = "Co2 " + co2Total;
document.querySelector('.animals').innerHTML = "Animals " + animalTotal;
};

Code Pen

关于javascript - 更新输入数字变量 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30984843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com