如何获取url的参数

如何获取url的参数

本文介绍了jQuery:如何获取url的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于jQuery而言,我无法获取服务器生成的url参数。我有这样一个网址:

 < span class =popuptest>< a href =www.example .com / test?param1 = 1& param2 = 2>找到参数< / a>< / span> 

我的jquery函数看起来像这样:

  $(function(){
$('。popuptest a')。live('click',function(event){
$ .extend({ b $ b getUrlVars:function(){
var vars = [],hash;
var hashes = this.href.slice(this.href.indexOf('?')+ 1).split( '&');
for(var i = 0; i< hashes.length; i ++)
{
hash = hashes [i] .split('=');
vars.push(hash [0]);
vars [hash [0]] = hash [1];
}
return vars;
},
getUrlVar:function(name){
return $ .getUrlVars()[name];
}
});
var second = getUrlVars()[param2] ;
alert(second);
return false;
});
});

点击链接应该会显示2,但是我什么都没得到......任何帮助一个jQuery noob?在此先感谢!



我在博客上发现了这一点:

解决方案

您不需要使用纯jQuery的jQuery:

  function getParameterByName(name,href)
{
name = name.replace(/ [\ [] /,\\ \[)。更换(/[\]]/,\\\]);
var regexS =[\\?&]+ name +=([^&#] *);
var regex = new RegExp(regexS);
var results = regex.exec(href);
if(results == null)
return;
else
return decodeURIComponent(results [1] .replace(/ \ + / g,));
}

你可以用这种方式调用函数.. getParameterByName(param1,链接的href)




New to jQuery and I'm having trouble getting the parameters of a url that my server generates. I have a url like this:

<span class="popuptest"><a href="www.example.com/test?param1=1&param2=2">find param</a></span>

my jquery function looks like so:

$(function() {
  $('.popuptest a').live('click', function(event) {
  $.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = this.href.slice(this.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
      return vars;
    },
    getUrlVar: function(name){
      return $.getUrlVars()[name];
    }
  });
  var second = getUrlVars()["param2"];
  alert(second);
  return false;
  });
});

clicking on the link should show me "2", however I get nothing... any help for a jQuery noob? thanks in advance!

I found this on a blog: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

解决方案

You don't need jQuery for that purpose you can use the pure JavaScript:

function getParameterByName( name,href )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

and you can call the function in this way..getParameterByName(param1,href of your link)

DEMO

这篇关于jQuery:如何获取url的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:13