Javascript attach an onclick event to all links

后端 未结 7 1429
青春惊慌失措
青春惊慌失措 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:24

    Try using getElementsByTagName('a')

    0 讨论(0)
  • 2020-12-03 00:27

    Something like this should be useful for you:

    var elements = document.getElementsByTagName("a"),
        i,
        len,
        el;
    
    for (i = 0, len = elements.length; i < len; i++) {
        el = elements[i];
    
        // Do what you need on the element 'el'
    }
    
    0 讨论(0)
  • 2020-12-03 00:31

    I wanted to offer an improvement on @zatatatata's answer which also works with links with nested elements.

    function findLink(el) {
        if (el.tagName == 'A' && el.href) {
            return el.href;
        } else if (el.parentElement) {
            return findLink(el.parentElement);
        } else {
            return null;
        }
    };
    
    function callback(e) {
        const link = findLink(e.target);
        if (link == null) { return; }
        e.preventDefault();
        // Do something here
    };
    
    document.addEventListener('click', callback, false);
    

    If the clicked element isn't a link, we search its parents to check for a link element.

    0 讨论(0)
  • 2020-12-03 00:32
    function linkClickHandler(a) {
      console.log(a.host);
    }
    
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) links[i].onclick = function() {
        linkClickHandler(links[i]);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 00:36

    getElementsByTagName is supported by all modern browsers and all the way back to IE 6

    var elements = document.getElementsByTagName('a');
    for(var i = 0, len = elements.length; i < len; i++) {
        elements[i].onclick = function () {
            // stuff
        }
    }
    
    0 讨论(0)
提交回复
热议问题