Capturing all the click event

前端 未结 10 1553
无人共我
无人共我 2020-12-14 08:46

I am thinking of to add a javascript function to capture all the click events inside a html page.

So I am adding a global function that govern

10条回答
  •  轮回少年
    2020-12-14 09:17

    You need to take into account that a link can be nested with other elements and want to traverse the tree back to the 'a' element. This works for me:

    window.onclick = function(e) {
      var node = e.target;
      while (node != undefined && node.localName != 'a') {
        node = node.parentNode;
      }
      if (node != undefined) {
        console.log(node.href);
        /* Your link handler here */
        return false;  // stop handling the click
      } else {
        return true;  // handle other clicks
      }
    }
    

    See e.g. https://jsfiddle.net/hnmdijkema/nn5akf3b/6/

提交回复
热议问题