I am currently working on a HTML Calculator as part of the Odin Project.
I have encountered a weird behavior of .textContent: Here is my Code snippet from 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**
}
Problem is: Whenever I press + button, I still get an output (NaN) and I get an entry(NaN) into my input-array whoch should not happen.
Did I miss understood text.Content ?
The problem is this line:
if (e.key != "+" || e.key !="-" || e.key !="*" || e.key !="/") {
Let's simplify it to just two conditions:
if (e.key != "+" || e.key !="-") {
}
This will always be true
. If the key is +
, then it will not be -
, satisfying the second part. If the key is -
, then it will not be +
, satisfying the first part.
Use a string of keys instead, and check if the pressed key is included in it.
document.addEventListener('keydown', function (e) {
if ('+-*/'.includes(e.key)) {
Or, another option is to check if the key is a digit.
if (/\d/.test(e.key)) {
Demo:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.