Add Query-String parameter to static link on click

后端 未结 2 1334
南笙
南笙 2021-02-14 14:28

I\'m looking for a robust way of dynamically injecting a query string parameter when a visitor clicks on a static anchor-link.

For example a link:



        
2条回答
  •  悲哀的现实
    2021-02-14 15:10

    There are many ways you could do this. Below I've listed two very simple methods. Here I'm assuming you already have a reference to your a element (here I've called this element):

    Modifying the href attribute

    element.href += '?query=value';
    

    Using a click event listener

    element.addEventListener('click', function(event) {
        // Stop the link from redirecting
        event.preventDefault();
    
        // Redirect instead with JavaScript
        window.location.href = element.href + '?query=value';
    }, false);
    

提交回复
热议问题