首页 > 解决方案 > 使用 e.target 时,未定义不是对象

问题描述

我正在尝试使用 e.target 选择一个元素,但我收到错误“TypeError: undefined is not an object (evalating 'e.target')”

我的代码如下:

isRead();
    
function isRead(e) {
  if (e.target.classList.contains('isRead')) {
    console.log('it is read');
  }
}

function createBook(book) {
  const readBtn   = document.createElement('button');
  const readInput = document.getElementById('readInput');

  readBtn.classList.add('libraryBtn');
  readBtn.classList.add('read');
  readBtn.textContent = 'Read?'

  if (readInput.checked) {
    readBtn.textContent = 'Read';
    readBtn.classList.add('isRead')
  }

标签: javascript

解决方案


当你有一个没有回调的直接函数调用时,你为什么期望一个event对象被传递。e

isRead();

只有isRead当事件作为回调发生时调用该函数,您才能访问事件对象e

就像是:

document.querySelector('selectorElement').addEventListener("click",isRead);

推荐阅读