繁体   English   中英

JavaScript - textContent 实现

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM