点击移除按钮触发Uncaught TypeError: this.removeBook is not a function
报错根因
你写在onclick属性内的代码运行时,this指向的是触发点击事件的按钮DOM元素,而非Library类的实例,因此找不到定义在Library类上的removeBook方法,这就是调用失败的核心原因。
修复方案
推荐使用事件绑定替代行内onclick写法,保证this正确指向Library实例,修改createBook方法即可:
createBook = ({ title, author, id }) => { const div = document.createElement('div'); div.innerHTML = ` <h3>${title}</h3> <h3>${author}</h3> <button class="delete btnDelete p-1 rounded" id="${id}">Remove</button> <hr> `; // 手动绑定点击事件,箭头函数继承当前作用域的this(即Library实例) div.querySelector('.btnDelete').addEventListener('click', (e) => { this.removeBook(e.target); }); document.querySelector('.output').appendChild(div); };
如果不想改动太多代码,也可以直接修改行内onclick的写法,直接调用全局定义的library实例方法:
<button class="delete btnDelete p-1 rounded" id="${id}" onclick="library.removeBook(this)">Remove</button>
该方法依赖全局实例变量,封装性不如第一种方案,仅作临时修复参考。
内容的提问来源于stack exchange,提问作者Qoosim
相关产品推荐
相关产品推荐

