[英]onchange doesn't work automatically when an input changes
我正在寫一個JavaScript來根據用戶輸入來計算價格,並根據所計算的價格來計算總價格。 我不想放onchange =“ 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>
如果您使用的是Jquery,請嘗試使用委托 。 這是一個簡單的例子。
下面是html。
user input:<input type="text" id="user-input">
以下是javascript。
$( "body" ).delegate( "#user-input", "onchange", function() {
//your code here.
});
我的答案只會使onchange()
事件觸發,剩下的邏輯必須編寫。
這是另一個使用JavaScript的示例。 我已經嘗試過,並且工作正常。
以下是html代碼。
<input type="text" id="userinput" onchange="price();">
以下是JavaScript函數。
function price()
{
//your code here.
}
您可以在price()
執行所有計算,而不必使用單獨的Total()
。 由於price
和result
均為readonly
,因此用戶無法真正更改它們中的值。 因此,只需將代碼從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>
我根據您的代碼做了一個簡單的小提琴 ,並在兩個輸入之間應用了一個事件。 第二個輸入的分派類似於手動,因為它是只讀的。
function price() {
var a = parseInt(document.getElementById('user-input').value),
b = document.getElementById('calculation');
b.value = a + 10;
if (b.onchange)
b.onchange();
}
function Total() {
console.log('binded');
var b = parseInt(document.getElementById('calculation').value),
c = document.getElementById('result');
c.value = b*2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.