Javascript attach an onclick event to all links

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

提交回复
热议问题