[英]Javascript Calculator: How can I create an operator button based on a condition?
[英]How can I validate calculator input in real time in JavaScript before passing it to operator (=) function?
兩天來,我一直在嘗試在我的 JavaScript 計算器中實時驗證用戶輸入,然后再將整體輸入傳遞給operator(=) 函數。 我想要實現的是:我不希望用戶連續輸入一個以上的運算符號或點。 當用戶輸入每個輸入時,我希望計算器實時驗證每個輸入,這樣如果用戶連續輸入多個操作符或點,計算器將警告用戶並自動刪除最后一個輸入並更新驗證的輸入計算器屏幕。 例如;
1A) 22.3.2。 + 4 -6 **3 ++ 2-^ <-- 這是錯誤的(未驗證)
1B) 22.3+4-6*3+2 <-- 這就是我想要的(已驗證)
下面是我到目前為止編寫的示例代碼。
JavaScript
let userInput = "22.2. + 3 -4^"; //as the user is inputting, i want to be validating it in realtime
function validateWrongInput() {
let p = userInput;
for (i = 0; i < p.length; i++){
if ((p.charAt(i) === "!" || p.charAt(i) === "^" ||
p.charAt(i) === "*" || p.charAt(i) === "/" || p.charAt(i) === "+" ||
p.charAt(i) === "-" || p.charAt(i) === "(" || p.charAt(i) === ")") &&
(p.charAt(i - 1) === "!" || p.charAt(i - 1) === "^" ||
p.charAt(i - 1) === "*" || p.charAt(i - 1) === "/" ||
p.charAt(i - 1) === "+" || p.charAt(i - 1) === "-" ||
p.charAt(i - 1) === "(" || p.charAt(i - 1) === ")")) {
let a = p.split("");
a.pop();
let c = a.join("");
upDisplay.textContent = c; //This shows the user input as he is typing
updisplayResult = c;
downDisplay.textContent = "ERROR-Why Two Operators?"; // this shows the final result when the = sign is pressed
return true;
} else {
return false;
}
}
}
JavaScript
let userInput = "22.2. + 3 -4^"; //as the user is inputting, i want to be validating it in realtime
function validateDecimal() {
let p = userInput;
let pointCount = 0;
for (let i = 0; i < p.length; i++) {
if (p.charAt(i) !== "!" && p.charAt(i) !== "^" && p.charAt(i) !== "*" &&
p.charAt(i) !== "/" && p.charAt(i) !== "+" && p.charAt(i) !== "-") {
if (p.charAt(i) === "." && pointCount < 1) {
pointCount += 1
downDisplay.textContent = " ";
return "ok";
} else {
pointCount = 0;
let a = p.split("");
a.pop();
let c = a.join("");
upDisplay.textContent = c; //This shows the user input as he is typing
updisplayResult = c;
downDisplay.textContent = "ERROR-Why Two Operators?"; // this shows the final result when the = sign is pressed
return "ERROR-Why Two Operators?"+c;
}
} else {
pointCount = 0;
}
}
}
我正在尋找你的幫助。
const input = document.getElementById('userInput');
input.addEventListener('keydown', () => {
const p = input.value;
// validation...
})
聽起來您正在尋找事件偵聽器。 確保您有相應的 html input 元素,在這種情況下: <input type="text" id="userInput">
我相信最好讓用戶完成他們正在輸入的任何內容並在之后檢查。 這種行為可以通過使用事件偵聽器blur
或在submit
事件期間提交時進行驗證來實現(未解釋,但您可以查找或詢問)。
如果您一起制作正則表達式 (regEx),您可能會找到一種更好的方法來驗證您的字符串。 這有點復雜,只有當您對它們有信心時才應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.