Capturing all the click event

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

提交回复
热议问题