javascript - 使用 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')
}
解决方案
当你有一个没有回调的直接函数调用时,你为什么期望一个event
对象被传递。e
isRead();
只有isRead
当事件作为回调发生时调用该函数,您才能访问事件对象e
。
就像是:
document.querySelector('selectorElement').addEventListener("click",isRead);
推荐阅读
- django - 在 DateTimeField 字段中存储数据的正确方法是什么
- javascript - 如何解决`React Hook useEffect 缺少`react-hooks/exhaustive-deps`的依赖项?
- java - 如何在 Junit 5 jupiter 扩展中从我的测试中获取字段
- flutter - 当 Flutter 构建 web 文件时......不要在他的资产文件夹中插入资产图像
- android - 在图库中删除图像后如何触发广播接收器?
- c# - 使用 Net Core 默认 DI 注入字符串和服务
- c - 如何使用 GCC 强制枚举大小?
- python - 带有 NOT LIKE 查询的 SQLAlchemy CAST
- python - And_index 应该打印和的索引,但输出奇怪的东西
- scala - Akka StreamTcp 超时重启