jQuery事件捕获停止传播

问题描述 投票:1回答:2

我在父div上有一个事件监听器,我希望它也不会因为孩子div onclick而被解雇。

我正在使用jQuery,因为我需要.on()作为动态创建的元素,同时使用内联onclick =“myFunction()”动态创建子div。当onclick myFunction出现在孩子身上时,我不希望再次调用父.on(click)。

HTML:

    <div id="parent" class="areatext" onkeydown="checkR()">
    <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
    <div id="child" onclick="myFunction()"></div>
    </div>

js文件1:

$('#parent').on('click', function(event){
    $('#input').focus();
    console.log('parent clicked!');
    event.stopPropagation();
});

js文件2:

function myFunction(event){
   // actions
   // when this is clicked, #parent .on(click) also triggers, i don't want that
}
jquery event-handling stoppropagation
2个回答
1
投票

正如你所说,jQuery不支持在捕获阶段监听事件;你必须使用标准的Javascript而不是jQuery才能实现这一目标。例如:

const parent = document.querySelector('#parent');
parent.addEventListener('click', (e) => {
  if (e.target.matches('#child')) return;
  e.stopPropagation();
  console.log('parent was clicked, but not on child');
}, true);
function myFunction(event){
   console.log('child was clicked on');
   // when this is clicked, #parent .on(click) also triggers, i don't want that
}
<div id="parent" class="areatext">
  parent
  <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
  <div id="child" onclick="myFunction()">child</div>
</div>

1
投票

如果您希望在单击子div时不调用父div的单击处理程序,则必须在子div的单击事件处理程序中添加event.stopPropagation()

根据你的代码:

$('#parent').on('click', function(event){
    $('#input').focus();
    console.log('parent clicked!');
    //event.stopPropagation(); <-- Not needed
});

$('#parent').on('click', '.child', function(event){
    event.stopPropagation();
    // ^^^^ Add here
    console.log('child clicked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="areatext" onkeydown="checkR()">Parent
    <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>
    <div class="child">child</div>
</div>

我建议你阅读https://javascript.info/bubbling-and-capturing,了解如何使用JavaScript进行冒泡和捕获。

© www.soinside.com 2019 - 2024. All rights reserved.