当在Javascript中单击子元素时,如何覆盖父事件侦听器?

时间:2019-02-13 02:30:08

标签: javascript jquery override

如何在aFunction内覆盖child.js

我希望子事件侦听器在不触发aFunction的情况下触发,并且我无法修改parent.js

这有可能吗?

index.html:

       <th class="foo">foo &nbsp;&nbsp;

            <span class="bar" data-feather="arrow-down"></span>

        </th>

parent.js:

       parent = {
            init: function() {
                parent.aFunction($('.foo'));
            },
            aFunction: function(element) {
                element.on('click', function() {
                    alert('foo');
                });
            }, ...

         window.onload = parent.init;

child.js:

    $('.bar').on('click', function() {
      alert('bar');
    });

1 个答案:

答案 0 :(得分:2)

  • 首先,它的.bar不会引起称为bar的html标记
  • event.stopPropagation() 防止事件使DOM树冒泡,从而防止任何父处理程序收到该事件的通知。

示例

$('.foo').on('click', function() {
  alert('foo');
});
$('.bar').on('click', function(e) {
  e.stopPropagation();
  alert('bar');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">foo &nbsp;&nbsp;
    <span class="bar" data-feather="arrow-down">Bar</span>
</div>