Home  >  Q&A  >  body text

JavaScript click events only apply to the element itself, not its parent container

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粉545682500P粉545682500382 days ago449

reply all(1)I'll reply

  • P粉795311321

    P粉7953113212023-09-07 00:15:30

    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.

    reply
    0
  • Cancelreply