有多个事件委托时如何停止传播

时间:2018-12-03 10:33:23

标签: javascript jquery delegation

我有一个表行,其中有一个元素,其中一个事件处理程序委派给document元素,并且该行本身也有另一个处理程序委派给tbody元素。如下代码:

// first part is defined in an initiating script file, so no jQuery used.
document.addEventListener('click', function(e) {
    var el = e.srcElement || e.target;

    if (el && el.classList && el.classList.contains('gotocontact')) {
        e.stopPropagation();
        alert('going to contact...')
    }
})
// second part is defined after the jQuery included...
$('#list').on('click', 'tr', function() {alert('click tr...')})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
    <tbody id="list">
        <tr>
            <td><a class="gotocontact">John Doe</a></td>
            <td>Male</td>
        </tr>
        <tr>
            <td><a class="gotocontact">Jane Doe</a></td>
            <td>Female</td>
        </tr>
    </tbody>
</table>

我将stopPropagation放在了那里,但没有按我预期的那样工作:当我单击a元素时,不应触发tr处理程序。 任何人都可以提供一些提示吗?

3 个答案:

答案 0 :(得分:2)

如果您想阻止jQuery侦听器触发,则应在 captureing 阶段而不是在 bubbling 阶段调用stopPropagation,方法是传递一个true的第三个addEventListener自变量:

document.addEventListener('click', function(e) {
    var el = e.srcElement || e.target;

    if (el && el.classList && el.classList.contains('gotocontact')) {
        e.stopPropagation();
        alert('going to contact...')
    }
}, true)
// ^^^^ add third parameter

$('#list').on('click', 'tr', function() {alert('click tr...')})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
    <tbody id="list">
        <tr>
            <td><a class="gotocontact">John Doe</a></td>
            <td>Male</td>
        </tr>
        <tr>
            <td><a class="gotocontact">Jane Doe</a></td>
            <td>Female</td>
        </tr>
    </tbody>
</table>

答案 1 :(得分:0)

在您添加到“ tr”元素上的函数中添加stopPropagation。那应该工作

document.addEventListener('click', function (e) {
  var el = e.srcElement || e.target;
  if (el && el.classList && el.classList.contains('gotocontact')) {
  e.stopPropagation();
  alert('going to contact...')
 }
})
// second part is defined after the jQuery included...
$('#list').on('click', 'tr', function (e) {
 e.stopPropagation();
 alert('click tr...')
})

答案 2 :(得分:-1)

实际上,这里的问题是td标记内有a标记,而a标记的自然行为是将您带到了新页面,因此而不是使用{{ 1}}使用e.stopPropagation()。 希望对您有帮助。而且,您还可以在设置事件监听器的第三个参数中传递true。