【问题标题】:I have image in button and both button and image has separate onclick functions, when I click this image on button it also executes function on button [duplicate]我在按钮中有图像,按钮和图像都有单独的 onclick 功能,当我在按钮上单击此图像时,它也会在按钮上执行功能 [重复]
【发布时间】:2021-08-28 18:33:30
【问题描述】:
这是按钮。想象一下带有文本 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>
【问题讨论】:
标签:
javascript
html
function
button
onclick
【解决方案1】:
你的 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")
}
【解决方案2】:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;
charger=utf-8" />
<meta name="" content="">
<title></title>
</head>
<body>
<button id="btn" onclick="stack_fn(this)">
<img id="img" src="stack.png" alt="stack"
onclick="stack_fn(this)">
</button>
<script type="text/javascript" charset="utf-8">
function stack_fn(elm)
{
if(elm.id === "img")
alert(elm);
}
</script>
</body>
</html>