use javascript to intercept all document link clicks

前端 未结 3 864
深忆病人
深忆病人 2020-12-03 05:13

how do I intercept link clicks in document? it must be cross-platform.

I am looking for something like this:

// content is a div with innerHTML
var          


        
3条回答
  •  再見小時候
    2020-12-03 05:38

    What about the case where the links are being generated while the page is being used? This occurs frequently with today's more complex front end frameworks.

    The proper solution would probably be to put the click event listener on the document. This is because events on elements propagate to their parents and because a link is actually acted upon by the top-most parent.

    This will work for all links, whether they are loaded with the page, or generated dynamically on the front end at any point in time.

    function interceptClickEvent(e) {
        var href;
        var target = e.target || e.srcElement;
        if (target.tagName === 'A') {
            href = target.getAttribute('href');
    
            //put your logic here...
            if (true) {
    
               //tell the browser not to respond to the link click
               e.preventDefault();
            }
        }
    }
    
    
    //listen for link click events at the document level
    if (document.addEventListener) {
        document.addEventListener('click', interceptClickEvent);
    } else if (document.attachEvent) {
        document.attachEvent('onclick', interceptClickEvent);
    }
    

提交回复
热议问题