使用onclick调用removeItem函数时出现inventory未定义错误求助
问题解决:点击移除按钮时提示
inventory is not defined 错误原因
你用内联onclick="inventory.removeItem(${item.id})"时,代码会在全局作用域查找inventory变量,但你的库存实例大概率是在局部作用域(比如类内部、函数内部)创建的,并没有暴露到全局,所以触发点击时会找不到该变量。
推荐解决方案:使用addEventListener绑定事件(更规范,无作用域问题)
修改updateUI方法,放弃内联onclick,通过创建按钮元素并绑定事件监听器的方式实现,这样能保留当前类实例的this指向:
updateUI() { const itemsContainer = document.getElementById("items") as HTMLDivElement; if (!itemsContainer) return; itemsContainer.innerHTML = ""; this.items.forEach((item: Item) => { const itemElement = document.createElement("div") as HTMLDivElement; itemElement.className = "item"; // 创建名称展示元素 const nameElement = document.createElement("div"); nameElement.className = "item-name"; nameElement.textContent = item.name; // 创建移除按钮并绑定事件 const removeBtn = document.createElement("button"); removeBtn.className = "item-button"; removeBtn.textContent = "Remove"; // 箭头函数捕获当前实例的this,直接调用removeItem removeBtn.addEventListener("click", () => { this.removeItem(item.id); }); // 组装元素并添加到容器 itemElement.appendChild(nameElement); itemElement.appendChild(removeBtn); itemsContainer.appendChild(itemElement); }); }
备选方案:将实例暴露到全局(不推荐)
如果一定要用内联onclick,可以把你的库存实例挂载到window对象上,让全局作用域能访问到它:
// 假设你创建inventory实例的代码是这样的 const inventory = new YourInventoryClass(); // 挂载到全局 window.inventory = inventory;
这种方法会污染全局作用域,容易引发命名冲突,仅作为临时应急方案,不推荐在生产代码中使用。
内容的提问来源于stack exchange,提问作者Appicato
相关产品推荐
相关产品推荐

