[英]JavaScript - textContent implementation
我目前正在研究作為 Odin 項目一部分的 HTML 計算器。
我遇到了一個奇怪的 .textContent 行為:這是我的 JavaScript 代碼片段:
//---output is a HTML tag at which the input of the user should be entered-------------------------------
const output=document.querySelector('.Output');
//------I store the input (pressed keys) into an array
let input=[]
//-------------------------------------------------
//--------------keybord support--------------------
document.addEventListener('keydown', function(e) {
if (e.key != "+" || e.key !="-" || e.key !="*" || e.key !="/") {
let internalVariable = 0;
input.push(parseInt(e.key));
internalVariable=input.join('');
output.innerHTML=internalVariable;
}
if (e.key=="+") {
console.log(typeof e.key,input)**-> Test if condition works**
}
問題是:每當我按下 + 按鈕時,我仍然會得到一個輸出 (NaN) 並且我在我的輸入數組中得到一個條目 (NaN),這不應該發生。
我錯過了理解的 text.Content 嗎?
問題是這一行:
if (e.key != "+" || e.key !="-" || e.key !="*" || e.key !="/") {
讓我們將其簡化為兩個條件:
if (e.key != "+" || e.key !="-") {
}
這將永遠是true
。 如果鍵是+
,那么它不會是-
,滿足第二部分。 如果鍵是-
,那么它不會是+
,滿足第一部分。
改用一串鍵,並檢查按下的鍵是否包含在其中。
document.addEventListener('keydown', function (e) {
if ('+-*/'.includes(e.key)) {
或者,另一種選擇是檢查密鑰是否為數字。
if (/\d/.test(e.key)) {
演示:
const output = document.querySelector('.Output'); const input = [] document.addEventListener('keydown', function(e) { if (/\\d/.test(e.key)) { input.push(parseInt(e.key)); internalVariable = input.join(''); output.innerHTML = internalVariable; } else { console.log('do something when a non-digit was pressed'); } });
<div class="Output"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.