码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript原生获取URL参数的两种方法

时间:2018-03-28 15:35:26      阅读:414      评论:0      收藏:0      [点我收藏+]

标签:name   url   var   数字   split   cat   offset   cti   set   

通过url获取参数的两种原生方法(使用框架的话一般都会提供):

方法一(推荐):

  urlinfo=window.location.href; //获取当前页面的url

  len=urlinfo.length;//获取url的长度

  offset=urlinfo.indexOf("?");//设置参数字符串开始的位置

  newsidinfo=urlinfo.substr(offset,len)//取出参数字符串 这里会获得类似“id=1”这样的字符串

  newsids=newsidinfo.split("=");//对获得的参数字符串按照“=”进行分割

  newsid=newsids[1];//得到参数值

 

方法二:

  function getQueryStringArgs(){

  //取得查询字符串并去掉开头的问号

  var qs = (location.search.length > 0 ? location.search.substring(1) : ""),

    args = () ,

    items = qs.length ? qs.spilt("&") : [],

    items = null,

    name = null,

    value = null,

    i = 0,

    len = items.length;

  for(i=0;i < len; i++){

    item = item[i].split("=");

    name = decodeURIComponent(item[0]);

    value = decodeURIComponent(item[1]);

    if (name.length){

      args[name] = value;

    }

  }

  return args;

  }

 

JavaScript原生获取URL参数的两种方法

标签:name   url   var   数字   split   cat   offset   cti   set   

原文地址:https://www.cnblogs.com/CCLlog/p/8663680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!