Jquery : Append querystring to all links

前端 未结 2 1434
轻奢々
轻奢々 2020-12-08 21:53

I would like to append a query string onto all dynamic links within a page - to fix a bug in a old release - is this possible?

Any ideas?

相关标签:
2条回答
  • 2020-12-08 22:04

    Something like this?

    var querystring = 'myquerystringtoadd';
    
    $('a').each(function() {
        var href = $(this).attr('href');
    
        if (href) {
            href += (href.match(/\?/) ? '&' : '?') + querystring;
            $(this).attr('href', href);
        }
    });
    

    Working example.

    0 讨论(0)
  • 2020-12-08 22:20

    This solution with native javascript :

    var querystring = 'yourQueryStringHere=;-)';
    
    document.addEventListener('click', function (e) {
    
        var x = e.originalTarget;
        if (x.nodeName === 'A') {
    
            var href = x.getAttribute('href');
    
            if(href) {
                href += (/\?/.test(href) ? '&' : '?') + querystring;
                x.setAttribute('href', href);
            }
        }
    
    }, false);
    
    0 讨论(0)
提交回复
热议问题