JS拼接a标签onclick事件触发Unexpected token 'return'报错如何解决
问题解决方法
你的报错本质是字符串拼接时多层引号嵌套冲突,外层JS拼接字符串、HTML属性、属性内的JS代码三层都用到了引号,没有正确转义导致语法解析失败,同时原代码缺少href属性值的引号包裹,也是元素无法正常显示的原因之一。
方案1:使用ES6模板字符串(最简便)
用反引号包裹外层拼接字符串,直接通过${变量名}`插入动态参数,无需处理加号拼接和常规引号的转义冲突:
content += `<a href="${delete_url}" onclick="return confirm('Are you sure you want to delete this item?');"><button class="w-11/12 text-xs text-center text-white mx-auto bg-purple-900 py-1 px-2 rounded-xl"><i class="far fa-images"></i></button></a>`;
方案2:兼容旧环境的转义写法
如果不能使用ES6语法,给内层嵌套的单引号加转义符\,同时给href属性值补充双引号包裹:
content += '<a href="' + delete_url + '" onclick="return confirm(\'Are you sure you want to delete this item?\');"><button class="w-11/12 text-xs text-center text-white mx-auto bg-purple-900 py-1 px-2 rounded-xl"><i class="far fa-images"></i></button></a>';
方案3:独立绑定事件(更易维护,推荐)
不建议把事件逻辑写在HTML字符串里,可单独创建DOM元素后绑定点击事件,避免引号冲突的同时方便后续逻辑修改:
// 创建a标签元素 const deleteLink = document.createElement('a') deleteLink.href = delete_url deleteLink.innerHTML = '<button class="w-11/12 text-xs text-center text-white mx-auto bg-purple-900 py-1 px-2 rounded-xl"><i class="far fa-images"></i></button>' // 绑定删除确认事件 deleteLink.addEventListener('click', () => confirm('Are you sure you want to delete this item?')) // 插入到目标容器 document.querySelector('你的目标容器选择器').appendChild(deleteLink)
内容的提问来源于stack exchange,提问作者artiest
相关产品推荐
相关产品推荐

