按钮内嵌带独立点击事件的图片,点击图片时如何阻止触发按钮事件
问题根因
该现象由DOM事件冒泡机制导致:子元素触发的事件会默认逐层向上传递给所有父级元素,点击内嵌在button内的图片时,图片的点击事件执行完成后,事件会向上冒泡到父级button元素,触发button绑定的clickcustomer函数。
解决方案
方案1:行内直接阻止冒泡(最快生效)
在图片的onclick属性中,执行自定义函数前添加event.stopPropagation()即可阻断事件向上传递,修改后代码如下:
<button onclick="clickcustomer(this.id)" id="addedprivatecustomerbutton1" class="addedprivatecustomerbutton displaynone" type="button" name="button">B2C01 <img class="removeaddedcustomerbutton" id="addedprivatecustomersvgsvg1" src="img\removeaddedcustomerbutton.svg" alt="" onclick="event.stopPropagation();removeprivatecustomer(this.id)"> </button>
方案2:在移除函数内阻止冒泡(可维护性更高)
修改removeprivatecustomer函数,接收事件参数并在逻辑开头阻断冒泡:
function removeprivatecustomer(id, event) { event.stopPropagation() // 原有移除按钮的逻辑保持不变 }
同步修改img的onclick属性传入事件对象:
<img ... onclick="removeprivatecustomer(this.id, event)">
内容的提问来源于stack exchange,提问作者OgLuka
相关产品推荐
相关产品推荐

