gpt4 book ai didi

javascript - 为什么我的函数无法获取变量的值?

转载 作者:行者123 更新时间:2023-12-03 00:08:18 27 4
gpt4 key购买 nike

该代码的目的是计算汽车市场值(value)。如果如果汽车的年龄是:1 - 然后从汽车价格中减去 20%2 - 然后从汽车价格中减去 35%3 - 7 - 然后从汽车价格中减去 35%,然后减去 10%从第三年开始,每年增加。8 - 10 - 那么市值固定为100,000.0010多年之后市值就固定在75,000.00。

然后会显示输入的名称和汽车的值(value),但似乎不起作用。请帮忙

var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
var condition = document.getElementById("condition").value;
var name = document.getElementById("name").value;

age = parseInt(age);
condition = parseInt(condition);

function calculateValue() {
switch (age) {
case 0:
price = price - 0.20 * price;
break;
case 1:
price = price - 0.35 * price;
break;
case 2:
price = price - 0.35 * price - (age - 3) * .10 * price;
break;
case 3:
price = 100000;
break;
case 4:
price = 75000;
break;
}

switch (condition) {
case 0:
price = price;
break;
case 1:
price = price - price * .10;
break;
}

document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}
<h1>Car Market Value Calculator</h1>
<form>
Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br> Age of Car
<select id="age">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3-7</option>
<option value="3">8-10</option>
<option value="4">more than 10</option>
</select><br> Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000"><br>
<p>Good Condition?</p>
Yes <input id="condition" type="radio" name="condition" value="0"> No <input id="condition" type="radio" name="condition" value="1">
<button type="button" name="submit" onclick="calculateValue()">Submit</button>

</form>
<p id="message"></p>

最佳答案

您的代码中有一些错误:

  1. 您没有在正确的时刻从 dom 获得输入。您应该在计算之前获取输入值,而不是在脚本加载时获取。这可确保 DOM 已加载并获取正确的值。

  2. age 值计算不正确。不要对数值使用 select。另外,请再次阅读您的案例价格 = 2 ;)

此代码符合您的预期:

const calculateValue = () => {
let age = +document.querySelector('input[name=age]').value,
price = +document.querySelector('input[name=price]').value,
condition = document.querySelector('input[name=condition]').checked;

// depreciate based on age
if (age==1) price*=.8
else if (age==2) price*=.65
else if (age>2 && age<8) price*=(.65-(age-3)*.1)
else if (age>7 && age<11) price = 100000
else price = 75000;

// depreciate based on condition
if (!condition) price*=.9;

console.log(price);
}
<div>
<input name="age" type="number" placeholder="age">
</div>
<div>
<input name="price" type="number" placeholder="price">
</div>
<div>
Good condition?
<input name="condition" type="radio" value="true" checked>yes
<input name="condition" type="radio" value="false">no
</div>
<button onclick="calculateValue()">Compute</button>

关于javascript - 为什么我的函数无法获取变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54866041/

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