Odoo 14出现Uncaught TypeError: 无法读取undefined的appendChild属性问题
问题解决:Odoo 14 对话框弹出代码报错修复
错误原因分析
你遇到的Cannot read properties of undefined (reading 'appendChild')错误,核心问题有两个:
- 错误调用容器元素:你通过
const container = document.createElement('div')创建的是局部变量,并非document对象的属性,不能用document.container访问,直接使用变量名container即可调用appendChild方法 - 存在拼写错误:
author.inertText应为author.innerText
另外还有两处可优化的细节:
- 样式里的选择器
#notification-container和容器实际IDcontainer不匹配,需要统一 - 关闭按钮未设置文本,用户无法识别按钮功能
修正后的完整代码
notificationDialogPopup: function(data){ if(data){ const container = document.createElement('div'); container.setAttribute("id","notification-container"); // 统一ID与样式选择器 const title = document.createElement('h1'); title.setAttribute("id", "title"); title.innerText = "Title Testing"; const content = document.createElement('p'); content.setAttribute("id","content"); content.innerText = "Content Testing"; const date = document.createElement('h6'); date.setAttribute("id","date"); date.innerText = "11-11-1999"; const author = document.createElement('h6'); author.setAttribute("id","author"); author.innerText = "Admin"; // 修正拼写错误 const btnClose = document.createElement('button'); btnClose.setAttribute("id","button"); btnClose.innerText = "关闭"; // 添加按钮文本,明确功能 const style = document.createElement('style'); style.innerHTML = "#notification-container {padding: 20px; border: 1px solid #ccc; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; z-index: 9999;}" + "#title {color:red}" + "#content {color:blue}" + "#date {color:red}" + "#author {color:red}" + "#button {margin-top: 15px; padding: 8px 16px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;}" // 直接使用局部变量container添加子元素 container.appendChild(title); container.appendChild(content); container.appendChild(date); container.appendChild(author); container.appendChild(btnClose); document.head.appendChild(style); document.body.appendChild(container); // 可选:添加关闭按钮点击事件,点击后移除弹窗 btnClose.addEventListener('click', function() { container.remove(); }); } }
额外说明
- 给容器添加了基础弹窗样式(居中布局、背景色、层级),让弹窗更符合视觉预期
- 补充了关闭按钮的点击逻辑,点击后可移除弹窗元素
- 所有子元素均正确添加到容器后,再将容器挂载到页面body中
内容的提问来源于stack exchange,提问作者WilliamVietnam
相关产品推荐
相关产品推荐

