给jQuery Popover默认模板添加ID触发Cannot read property 'remove'报错如何解决
错误原因
Bootstrap Popover 内部会对模板结构做固定节点查找,同时会自动计算定位属性并写入元素样式:
- 你在自定义template里硬编码了
position、transform、inset等定位相关的内联样式,导致内部渲染逻辑紊乱,查找对应DOM节点失败,调用remove方法时拿到了null值,触发报错。 - 如果你使用的是Bootstrap 5版本,
customClass配置项已更名为customClasses,配置项名称不匹配也可能触发渲染异常。
解决方案
方案1:修改自定义模板
保留模板的默认结构,仅添加自定义ID,删除硬编码的定位样式即可:
$("#myElement").popover({ trigger: "manual", placement: placement, html: true, template: `<div id="${id}" class="popover fade bs-popover-end"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>`, customClass: customClass, // 若为Bootstrap 5请改为customClasses content: content, })
方案2:通过事件动态添加ID(更稳妥)
不修改默认模板,在popover弹出完成的事件中给生成的元素添加ID,完全不侵入Popover的内部渲染逻辑,兼容性更强:
// 初始化popover用默认配置即可 $("#myElement").popover({ trigger: "manual", placement: placement, html: true, customClass: customClass, content: content }) // 监听弹出事件,动态添加自定义ID $("#myElement").on('shown.bs.popover', function () { // 取最新生成的popover元素设置ID document.querySelector('.popover:last-of-type').id = id })
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

