Capturing all the click event

前端 未结 10 1548
无人共我
无人共我 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:24

    Use event delegation:

    document.addEventListener(`click`, e => {
      const origin = e.target.closest("a");
      
      if (origin) {
        console.clear();
        console.log(`You clicked ${origin.href}`);
      }
    });
    <div>
      <a href="#l1">some link</a>
      <div><a href="#l2"><div><i>some other (nested) link</i></div></a></div>
    </div>

    [edit 2020/08/20] Modernized

    0 讨论(0)
  • 2020-12-14 09:24
    ​window.onclick = function (e) {
        if (e.target.localName == 'a') {
            console.log('a tag clicked!');
        }
    }​
    

    The working demo.

    0 讨论(0)
  • 2020-12-14 09:24

    Try jQuery and

    $('a').click(function(event) { *your code here* });
    

    In this function you can extract href value in this way:

    $(this).attr('href')
    
    0 讨论(0)
  • 2020-12-14 09:26

    You can also try using this:

    var forEach = Array.prototype.forEach;
    var links = document.getElementsByTagName('a');
    forEach.call(links, function (link) {
        link.onclick = function () {
            console.log('Clicked');
        }
    
    });
    

    It works, I just tested!

    Working Demo: http://jsfiddle.net/CR7Sz/

    Somewhere in comments you mentioned you want to get the 'href' value you can do that with this:

    var forEach = Array.prototype.forEach;
    var links = document.getElementsByTagName('a');
    forEach.call(links, function (link) {
        link.onclick = function () {
            console.log(link.href); //use link.href for the value
        }
    
    });
    

    Demo: http://jsfiddle.net/CR7Sz/1/

    0 讨论(0)
提交回复
热议问题