JavaScript click events only apply to the element itself, not its parent container
P粉545682500
P粉545682500 2023-09-06 18:50:37
0
1
506

I have the following code:

<div onclick="myFunc()" style="height:200px;width:200px;">
  <button></button>
</div>

I want myFunc to be executed when anywhere on the div is clicked, but not the button. How can I achieve this?

P粉545682500
P粉545682500

reply all(1)
P粉795311321

In the button click event, you need to cancel event propagation. Or stop "bubbling".

See https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

So in your button's click event, you need to be like this:

function button_click(event) {
    event.stopPropagation();
    console.log("按钮被点击了。");
  }

By default, the click event of an element will be passed to its parent element.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template