jQuery:如何获取 url 的参数? [英] jQuery: How to get parameters of a url?

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

问题描述

我是 jQuery 新手,但在获取服务器生成的 url 参数时遇到问题.我有一个这样的网址:

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>

我的 jquery 函数如下所示:

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;
  });
});

点击链接应该会显示2",但是我什么也没得到……对 jQuery 菜鸟有什么帮助吗?提前致谢!

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

我在博客上找到了这个:http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

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

推荐答案

为此您不需要 jQuery,您可以使用纯 JavaScript:

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, " "));
}

你可以这样调用函数..getParameterByName(param1,href of your link)

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

演示

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆