【问题标题】:JavaScript - textContent implementationJavaScript - textContent 实现
【发布时间】:2021-09-04 13:56:28
【问题描述】:

作为 Odin 项目的一部分,我目前正在开发 HTML 计算器。

我遇到了 .textContent 的奇怪行为:这是我的 JavaScript 代码 sn-p:

//---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 吗?

【问题讨论】:

  • 您询问textContent,但您的代码没有使用它...

标签: javascript arrays dom


【解决方案1】:

问题出在这一行:

if (e.key != "+" || e.key !="-" || e.key !="*" || e.key !="/") {

让我们将其简化为两个条件:

if (e.key != "+" || e.key !="-") {
}

这将永远是true。如果key是+,那么就不是-,满足第二部分。如果key是-,那么就不是+,满足第一部分。

改为使用一串键,并检查按下的键是否包含在其中。

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>

【讨论】:

  • 当一个答案解决了您的问题时,您可以考虑将其标记为已接受(选中左侧的复选框)以表明问题已解决:)
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 2015-07-02
  • 2020-12-31
  • 1970-01-01
  • 2016-07-13
  • 2013-08-22
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多