簡體   English   中英

錨上的委托點擊事件

[英]Delegated click event on anchors

我正在嘗試定位錨標記並觸發ajax請求。 使用jQuery,這非常簡單:

$(document.body).on('click', "a", function (event) {
    'use strict';
    if ($(this).is('.a-btn')) {
        event.preventDefault();
    } else if ($(this).is('.no-sp')) {
        //
    } else {
        address = $(this).attr("href")
        event.preventDefault();
        App.Ajax.Page(address + '/');
    }
});

但是,使用本地javascript,我可以想象使用event.target可以達到目的。

但這是行不通的,因為事件始終以錨標記內的任何元素為目標:

App.Ajax.Navigate = function () {
    'use strict';
    document.body.addEventListener('click', function (e) {
        e.preventDefault();
        console.log(e.currentTarget);
        if (e.target.tagName === 'a') {
            var element, link;
            element = e.target;
            link = element.href;

            if (App.HTML.hasClass(element, 'a-btn')) {
                e.preventDefault();
            } else if (App.HTML.hasClass(element, 'no-sp')) {
                return;
            } else {
                e.preventDefault();
                App.Ajax.Page(link);
            }

        }
    }, true);

    window.onpopstate = function (event) {
        App.Page.type = event.state.type;
        App.Page.Replace(event.state.content, event.state.type, App.Empty, false);
    };
};

我想使用本機javascript來執行第一個代碼段中的jQuery,這可能嗎?

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
https://developer.mozilla.org/ru/docs/Web/API/Element/closest-2個策略填充

event.target.closest("a")

對於大多數瀏覽器,請不要忘記使用polifill。


(function(e){ 
  if (!e.matches) {
    e.matches = e.mozMatchesSelector || e.msMatchesSelector || e.oMatchesSelector || e.webkitMatchesSelector;
  }

  if (!e.closest) {
    e.closest = function (css) { 
      for (var node = this; node; node = node.parentElement) { 
        if (node.matches(css)) {
          return node; 
        }
      }

      return null; 
    } 
  }
})(Element.prototype);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM