Javascript attach an onclick event to all links

后端 未结 7 1554
青春惊慌失措
青春惊慌失措 2020-12-03 00:12

I want to attach a function on every link on the site to change a parameter.

How can I do this without jQuery?

How do I traverse every link (it might be a DO

7条回答
  •  情话喂你
    2020-12-03 00:34

    It's weird that nobody offered an alternative solution that uses event bubbling

    function callback(e) {
        var e = window.e || e;
    
        if (e.target.tagName !== 'A')
            return;
    
        // Do something
    }
    
    if (document.addEventListener)
        document.addEventListener('click', callback, false);
    else
        document.attachEvent('onclick', callback);
    

    The pros of this solution is that when you dynamically add another anchor, you don't need to specifically bind an event to it, so all links will always fire this, even if they were added after these lines were executed. This is in contrast to all the other solutions posted so far. This solution is also more optimal when you have a large number of links on your page.

提交回复
热议问题