[英]How can I get the value of 2 inputs, calculate them and put the result in another
我需要重構此代碼以提高性能,我取兩個輸入的值,我需要計算它們並將其顯示在另一個
var price;
var percentage;
var value;
function total() {
value = ((price* (percentage/ 100)) + parseFloat(price));
$("#Total").val(value.toFixed(2));
}
$("#price").keyup(function () {
price= $(this).val();
total()
});
$("#percentage").keyup(function () {
percentage= $(this).val();
total()
});
你不應該使用這樣的全局變量,它們可能會導致競爭條件。
// this self executing function will prevent the *Field variables to be bound to your browsers' window variable.
(function() {
let priceField = $("#price");
let percentageField = $("#percentage");
let totalField = $("#Total");
function total() {
let price = priceField.val();
let percentage = percentageField.val();
let value = (price * (percentage/ 100)) + parseFloat(price);
totalField.val(value.toFixed(2));
}
priceField.keyup(function () {
total()
});
percentageField.keyup(function () {
total()
});
})()
我不得不說,這是您問題的解決方案,但它不是最好的解決方案。 但根據我的猜測,這個解決方案需要簡單。
一些額外的提示是有選擇地搜索像$("input#price")
這樣的輸入字段,以防止任何其他潛在的沖突,盡管 id 應該是唯一的。
我還建議在代碼中添加一些保護。 如果有人輸入了一些非數值,會發生什么。 是否應該在進行計算之前從輸入中刪除它們,或者它們是否應該向用戶觸發錯誤,指出用戶的輸入無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.