JQuery: intercepting a going link and adding parameters

When the user clicks on the link on my page, I need, before it is activated by the browser, add the Hello = True parameter to the url.

So, the user clicks MyPage.aspx and goes to MyPage.ASPX? Hi = True.

Must be client side, preferably using jQuery

I can add an attribute to tags if necessary.

Yang

+6
jquery
source share
6 answers

if you need all the links to manage, use this:

$('a').each(function() { var href = this.href; if (href.indexOf('?') != -1) { href = href + '&Hello=True'; } else { href = href + '?Hello=True'; } $(this).attr('href', href); }); 
+9
source share

You can change all the links on your page as follows:

 $("a").each(function() { $(this).attr("href", $(this).attr("href") + '?Hello=True')); }); 

If you want to redirect the user with these added parameters when clicking on the hyperlink, use this:

 $("a").click(function(e) { e.preventDefault(); window.location.href = $(this).attr("href") + '?Hello=True'; }); 
+9
source share

Cleaner / shorter / better version of @Jan Willem B version:

 $('a').each(function(){ var sep = (this.href.indexOf('?') != -1) ? '&' : '?'; $(this).attr('href', href + sep + 'Hello=True'); }); 

You can also place the statement on one line, sacrificing readability:

 $('a').each(function(){ $(this).attr('href', href + ((this.href.indexOf('?')!=-1)?'&':'?') + 'Hello=True'); }); 

What is it

+4
source share

I tried a clean version of @arnorhs, and although it is cleaner and more compact, there is a slight perplexity in the code, since href should be this.href:

 $('a').each(function(){ var sep = (this.href.indexOf('?') != -1) ? '&' : '?'; $(this).attr('href', this.href + sep + 'Hello=True'); }); 

and

 $('a').each(function(){ $(this).attr('href', this.href + ((this.href.indexOf('?')!=-1)?'&':'?') + 'Hello=True'); }); 

In a similar vein, the more compact version commented on by @Jan Willem B has this minor issue twice and should read:

 $('a').each(function(){ var sep = (this.href.indexOf('?') != -1) ? '&' : '?'; $(this).attr('href', this.href + sep + 'Hello=True'); }); 

Otherwise, both posts and comments look great, and the (latest) compact version works beautifully (did not test the rest).

NOTE. Due to the threshold of reputation points, I had to post a comment or comment. NTN.

0
source share

Here is what I was trying to do to add a parameter to the url that contains a specific character in the url.

 [jsfiddle]: http://jsfiddle.net/nasabikram/prswd16k/2/ 
0
source share

You cannot change the URL using JavaScript without redirecting.

You can use window.location=url;

And also you can look at this site: http://ajaxpatterns.org/Unique_URLs

-one
source share

All Articles