开发者

How to add name value pair to existing query string

开发者 https://www.devze.com 2023-04-03 06:01 出处:网络
i need to add new name ,value pair to existing que开发者_如何学JAVAry string when the user click on some button.

i need to add new name ,value pair to existing que开发者_如何学JAVAry string when the user click on some button.

i'm using jquery for client side operations.

any idea..?

thank in advance!


You could do:

$('#yourId').click(function(){
   var href = window.location.href;
var indexOfCanc = href.indexOf('#');
if(indexOfCanc === -1){
  if(href.indexOf('?') === -1){
     href+="?newparamter=my";
  }else{
     href+="&newparamter=my";
  }
 }else{
  var newHref = href.substring(0, indexOfCanc);
  var locationHash = href.substring(indexOfCanc); 
  if(href.indexOf('?') === -1){
     newHref += "?newparamter=my"+locationHash;
  }else{
     newHref += "&newparamter=my"+locationHash;
  }
 }   


   //use the new href for example reload the page with the new parameter:
   window.location.href = href;
});


Using regExp:

var href = window.location.href,
    toAdd,
    pattern1 = /\?/gi,
    pattern2 = /#/gi;
if (href.match(pattern1) != null) { toAdd = "&" }
else { toAdd = "?" }
toAdd += "param=val";
if (href.match(pattern2) != null) {
    var arr = href.split('#');
    href = arr[0] + toAdd + '#' + arr[1];
}
else { href += toAdd; }
0

精彩评论

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

关注公众号