Add Query-String parameter to static link when clicked

I am looking for a reliable way to dynamically enter a query string parameter when a visitor clicks on a static binding.

For example, the link:

<a href="http://www.johndoeslink.com">Test</a> 

I want to pass the query string to the next page, but I need to assign the value dynamically. How can I achieve this?

I know this is simple, I just missed something obvious! = \

Thanks in advance,

John d

+6
source share
2 answers

There are many ways to do this. Below I have listed two very simple methods. Here I assume that you already have a reference to your element a (here I called it element ):

Change href attribute

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

Using the 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); 
+9
source

If you already know the value to add at page load, you can add this when the document is ready: if you are using jQuery, use this:

 $( 'class' ).attr( 'href', function(index, value) { return value + '?item=myValue'; }); 

Otherwise (regular Javascript):

 var link = document.getElementById("mylink"); link.setAttribute('href', 'http://www.johndoeslink.com'+'?item=myValue'); 
+2
source

Source: https://habr.com/ru/post/973771/


All Articles