单击子级时阻止父级单击

Mag*_*Mag 2 javascript jquery

我想在单击子 SPAN 时阻止父级单击。我试过

    e.stopPropagation

    and thi way

    if (!e) e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
Run Code Online (Sandbox Code Playgroud)

我有像这样的html:

 <label for="parent_id"> Some text
   <span id="child_id">Click child</span>
 </label>
 <input id="parent_id" />
Run Code Online (Sandbox Code Playgroud)

父元素的函数

$('#parent_id').click(function (e) { SomeParentCode }

子元素的函数。

$('#child_id').click(function (e) {
      e.stopPropagation();
       But I what to prevent parent click
       SomeChildCode
}
Run Code Online (Sandbox Code Playgroud)

JF *_* it 7

使用 PreventDefault 和 stopPropagation。

$('#child_id').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)


Yur*_*nko 5

您需要通过调用来防止默认操作(专注于输入)ev.preventDefault

$(function() {
  $('#child').click(e => {
    e.preventDefault()
    
    console.log('click on child')
  })
  
  $('#parent').click(() => {
    console.log('click on parent')
  })

})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="parent">
  <span id="child">Click Me</span>
</label>
<input type="text" id="parent">
Run Code Online (Sandbox Code Playgroud)