将类添加到HTML标记(<p>)会返回错误

时间:2017-12-30 22:42:00

标签: javascript html css dom

我正在尝试将类添加到HTML标记(<p></p>),但是当我运行代码时,它会返回错误:

  

未捕获的TypeError:无法读取null

的属性'classList'

window.addEventListener('keydown', onKeydown);

const num_ok = [13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
const del_ = 46;
const back_ = 8;

function getElementByKeyCode(keyCode) {
  return document.querySelector(`[data-key = '${keyCode}']`); //tag <p></p>
}

function changeColor(keyCode, opts = {}) {
  const element = getElementByKeyCode(keyCode);

  if (opts.num || opts.ok) {
    element.classList.add('green'); //error when keydown
  } else if (opts.del) {
    element.classList.add('red'); //error when keydown
  } else if (opts.back) {
    element.classList.add('yellow'); //error when keydown
  }

  setTimeout(() => {
    deactive(element)
  }, 1000);
}

function deactive(element) {
  element.className = "num";
}

function onKeydown(event) {
  if (num_ok.includes(event.keyCode)) {
    changeColor(event, {
      num: true,
      ok: true
    });
  } else if (event.keyCode == del_) {
    changeColor(event, {
      del: true
    });
  } else if (event.keyCode == back_) {
    changeColor(event, {
      back: true
    });
  }
}
.num {
  color: #fff;
}
p.red {
  color: #e74c3c;
}
p.yellow {
  color: ffc300;
}
p.green {
  color: #2ecc71;
}
<div class="btns" id="n1">
  <p class="center normal num" data-key="49">1</p>
</div>

1 个答案:

答案 0 :(得分:0)

调用changeColor()时,您正在传递整个事件而不是event.keyCode。我可以看到你只有num1键击所需的元素,但你没有相同的其余数字。我猜这只是问题的简短版本。

&#13;
&#13;
window.addEventListener('keydown', onKeydown);

const num_ok = [13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 190];
const del_ = 46;
const back_ = 8;

function getElementByKeyCode(keyCode) {
  return document.querySelector(`[data-key = '${keyCode}']`); //tag <p></p>
}

function changeColor(keyCode, opts = {}) {
  const element = getElementByKeyCode(keyCode);

  if (opts.num || opts.ok) {
    element.classList.add('green'); //error when keydown
  } else if (opts.del) {
    element.classList.add('red'); //error when keydown
  } else if (opts.back) {
    element.classList.add('yellow'); //error when keydown
  }

  setTimeout(() => {
    deactive(element)
  }, 1000);
}

function deactive(element) {
  element.className = "num";
}

function onKeydown(event) {
  if (num_ok.includes(event.keyCode)) {
    changeColor(event.keyCode, {
      num: true,
      ok: true
    });
  } else if (event.keyCode == del_) {
    changeColor(event, {
      del: true
    });
  } else if (event.keyCode == back_) {
    changeColor(event, {
      back: true
    });
  }
}
&#13;
.num {
  color: #fff;
}
p.red {
  color: #e74c3c;
}
p.yellow {
  color: ffc300;
}
p.green {
  color: #2ecc71;
}
&#13;
<div class="btns" id="n1">
  <p class="center normal num" data-key="49">1</p>
</div>
&#13;
&#13;
&#13;