首页 > 解决方案 > 我在按钮中有图像,按钮和图像都有单独的 onclick 功能,当我在按钮上单击此图像时,它也会在按钮上执行功能

问题描述

这是按钮。想象一下带有文本 B2C01 和旁边的 svg 的按钮,它的工作方式很接近。当我单击此图像时,按钮会消失,但同时会触发执行其他操作的按钮功能,并且会干扰我的代码。单击图像时如何阻止它执行?

    <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="removeprivatecustomer(this.id)"> </button>

标签: javascripthtmlfunctionbuttononclick

解决方案


您的 HTML 将是,

        <button onclick="clickcustomer()" 
        id="addedprivatecustomerbutton1"
        class="addedprivatecustomerbutton displaynone" type="button" name="button">B2C01
        <img class="removeaddedcustomerbutton" id="addedprivatecustomersvgsvg1" 
        src="img\removeaddedcustomerbutton.svg"
        alt="" onclick="removeprivatecustomer(event)"> </button>

JS会是,

  removeprivatecustomer(e){
    console.log("removeprivatecustomer")
    e.stopPropagation();
    console.log("removeprivatecustomer after stopPropagation")
  }

  clickcustomer(){
    console.log("clickcustomer")
  }

推荐阅读