search

Home  >  Q&A  >  body text

javascript - If the parent element is bound to click, how can the child element avoid triggering the click of the parent element without binding click?

HTML:

<p id="container">
  <p id="inner">

  </p>
</p>

JS:

document.getElementById('container').addEventListener('click',function () {
  document.getElementById('inner').style.display = "none";
});

When I click on the child element, it will disappear. How to avoid this situation? I don't want to bind click events to child elements as well.

扔个三星炸死你扔个三星炸死你2751 days ago867

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:24:56

    document.getElementById('container').addEventListener('click',function (e) {
      document.getElementById('inner').style.display = "none";
      e.stopPropagation();
    }, true);
    
    1. Pass the third parameter true to addEventListener. Use event capture.

      • https://developer.mozilla.org...

    2. e.stopPropagation() Stop event propagation.

      • https://developer.mozilla.org...

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-12 09:24:56

    https://jsfiddle.net/g5u7qrrd/6/

    document.getElementById('container')
        .addEventListener('click',function (e) {
            if (e.target.id !== 'inner')
                document.getElementById('inner').style.display = "none";
        });

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-12 09:24:56

    Add pointer-events: none;to the sub-element style and ignore mouse events directly. IE may need to be compatible.

    reply
    0
  • Cancelreply