DOM Events API:事件委托和stopPropagation [英] DOM Events API: event delegation and stopPropagation

查看:73
本文介绍了DOM Events API:事件委托和stopPropagation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是jQuery 1.7的代码:

this is a code with jQuery 1.7:

<div class="test">
  <div class="bu">
    <a>
      bu here
    </a>
  </div>
</div>
<script src="http://code.jquery.com/jquery-1.7.js"></script>
<script>
$(document).on('click', '.test', function () { alert(0); return false; });
$(document).on('click', '.bu', function () { alert(1); return false; });
$(document).on('click', '.bu', function () { alert(2); return false; });
</script>

点击.test> .bu将提醒1并提醒2,但不提醒0

clicking on .test > .bu will alert "1" and alert "2", but not alerts "0"

我的问题是:如何在没有jQuery的情况下(在原生DOM API上)做同样的事情?似乎,如果没有实现我自己的库,我无法使用Native DOM API ...

My question is: how to do the same WITHOUT jQuery (on native DOM API)? Seems, i can't do it with Native DOM API without implementing my own library...

谢谢!

推荐答案

<div class="a">
    <div class="b">
      <div class="c" style="border: 1px solid silver; width: 80px; text-align: center;line-height: 80px;">
          click me!
      </div>
    </div>
</div>

<script>

// Element.prototype.matchesSelector
(function (x) {
  var i;
  if (!x.matchesSelector) {
    for (i in x) {
      if (/^\S+MatchesSelector$/.test(i)) {
        x.matchesSelector = x[i];
        break;
      }
    }
  }
}(Element.prototype));

Document.prototype.on =
Element.prototype.on = function (eventType, selector, handler) {
  this.addEventListener(eventType, function listener(event) {
    var t = event.target,
      type = event.type,
      x = [];
    if (event.detail && event.detail.selector === selector && event.detail.handler === handler) {
      return this.removeEventListener(type, listener, true);
    }
    while (t) {
      if (t.matchesSelector && t.matchesSelector(selector)) {
        t.addEventListener(type, handler, false);
        x.push(t);
      }
      t = t.parentNode;
    }
    setTimeout(function () {
      var i = x.length - 1;
      while (i >= 0) {
        x[i].removeEventListener(type, handler, false);
        i -= 1;
      }
    }, 0);
  }, true);
};

Document.prototype.off =
Element.prototype.off = function (eventType, selector, handler) {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent(eventType, false, false, {selector: selector, handler: handler});
  this.dispatchEvent(event);
};

document.on('click', '.b', function () {
  alert(2);
});
document.on('click', '.a', function () {
  alert(1);
});
document.on('click', '.b', function (event) {
  alert(3);
  event.stopPropagation();
});

</script>

这篇关于DOM Events API:事件委托和stopPropagation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆