[英]JavaScript - textContent implementation
I am currently working on a HTML Calculator as part of the Odin Project.我目前正在研究作为 Odin 项目一部分的 HTML 计算器。
I have encountered a weird behavior of .textContent: Here is my Code snippet from JavaScript:我遇到了一个奇怪的 .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**
}
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.问题是:每当我按下 + 按钮时,我仍然会得到一个输出 (NaN) 并且我在我的输入数组中得到一个条目 (NaN),这不应该发生。
Did I miss understood text.Content ?我错过了理解的 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
.这将永远是
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.