JS insertAdjacentHTML插入带onclick的a标签报函数未找到错误
问题根因
点击a标签报函数找不到,是两个核心问题导致的:
- 内联
onclick属性执行时的上下文是全局作用域,只会在window对象上查找要调用的函数。你用const声明的removeItem属于局部/模块作用域变量,不会自动挂载到全局对象,所以触发时找不到对应函数。 - 就算解决了作用域问题,你写的
onclick="removeItem()"没有传入事件对象,函数内部访问e时会直接报undefined错误。 - 原有逻辑还有遗漏:取消复选框勾选时,没有同步移除已经生成的选中项a标签。
修复方案
不推荐用字符串拼接HTML+内联事件的写法,动态创建DOM节点后通过addEventListener绑定事件是更可靠的方案,完全不依赖全局作用域,同时补全取消勾选的同步删除逻辑:
修复后完整JavaScript代码
const removeItem = (e) => { e.preventDefault(); // 点击标签时同步取消对应复选框的选中状态 const currentLink = e.currentTarget; const matchCheckboxId = currentLink.id.replace('chosen-', ''); document.getElementById(matchCheckboxId).checked = false; currentLink.remove(); } document.querySelectorAll('.choose').forEach(choose => { choose.addEventListener('change', (e) => { const currentCheckbox = e.target; const selectedWrap = document.getElementById('selected'); const targetLinkId = `chosen-${currentCheckbox.id}`; if (currentCheckbox.checked) { // 创建DOM节点而非拼接HTML字符串 const selectedLink = document.createElement('a'); selectedLink.id = targetLinkId; selectedLink.href = ''; selectedLink.innerHTML = `${currentCheckbox.value}<i class="icon-close"></i>`; // 直接绑定事件,无需全局函数 selectedLink.addEventListener('click', removeItem); selectedWrap.appendChild(selectedLink); } else { // 取消勾选时同步移除对应选中项 const targetLink = document.getElementById(targetLinkId); targetLink?.remove(); } }) })
HTML部分无需修改,保持原有结构即可
<label> <input value="Value 1" id="1" class="choose" type="checkbox" data-np-invisible="1" data-np-checked="0" /> Add Value 1 </label> <div id="selected"></div>
如果你一定要保留内联onclick的写法,需要手动将函数挂载到全局作用域,同时传入事件参数:先执行
window.removeItem = removeItem,再把拼接的HTML里的onclick属性改成onclick="removeItem(event)"。但这种写法容易造成全局作用域污染,非必要不使用。
内容的提问来源于stack exchange,提问作者Ivana Murray
相关产品推荐
相关产品推荐

