开发者

jQuery: intercepting out going link and adding parameters

When a user clicks a link on my page, I need to, before it gets actioned by the browser, add the param Hello=True to the url.

So, the user clicks MyPage.aspx in and gets sent to MyPage.ASPX?H开发者_如何学JAVAello=True instead.

Has to be client side, preferably using jQuery

I can add an attribute to the tags if needed.

Ian


if you need all links to be manipulated, 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);
});


You can change all the links on your page like so:

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

If you want to redirect the user with those added parameters upon clicking a hyperlink use this:

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


A cleaner/shorter/better version of @Jan Willem B's version:

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

You could also place the statement in a single line, sacrificing readability:

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

That's that


I tried the cleaner version by @arnorhs and while it is cleaner and more compact there is a minor code omission as 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 in @Jan Willem B's post 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 (last) compact version works nicely (didn't test the others).

NOTE: Due to a reputation points threshold I had to post vs. comment. HTH.


Here is what i tried to do to add parameter in the url which contain the specific character in the url.

[jsfiddle]: http://jsfiddle.net/nasabikram/prswd16k/2/


You can't change URL with JavaScript without redirecting.

You can use window.location=url;

And also you may want to look this site : http://ajaxpatterns.org/Unique_URLs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜