gpt4 book ai didi

javascript - 当输入更改时 onchange 不会自动工作

转载 作者:行者123 更新时间:2023-12-03 03:45:05 25 4
gpt4 key购买 nike

我正在编写一个 JavaScript 来根据用户输入计算价格,并根据计算的价格计算总价。我不想把 onchange="Total();"进入用户输入,因为我希望 Total 函数自动区分价格输入的值变化。有办法做到这一点吗?

 <html>
user input:<input type="text" id="user-input" onchange="price();"><br>

price:<input type="text" id="calculation" onchange="Total();" readonly>
<br>


Total:<input type="text" id="result" readonly><br>

</html>

<script>
function price() {

var a = parseInt(document.getElementById('user-input').value),
b = document.getElementById('calculation');


b.value = a + 10;

}



function Total() {
var b = parseInt(document.getElementById('calculation').value),
c = document.getElementById('result');

c.value = b*2;
}

</script>

最佳答案

您可以在 price() 中执行所有计算,而不必使用单独的 Total()。由于 priceresult 都是只读,因此用户无法真正更改其中的值。因此,只需将代码从 Total() 移至 price() 即可。以下是更新后的代码:

function price() {
var a = parseInt(document.getElementById('user-input').value),
b = document.getElementById('calculation'),
c = document.getElementById('result')
b.value = a + 10;
c.value = b.value * 2;
}
user input:<input type="text" id="user-input" onchange="price();"><br> price:

<input type="text" id="calculation" readonly>
<br> Total:
<input type="text" id="result" readonly><br>

关于javascript - 当输入更改时 onchange 不会自动工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45430225/

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