3月 13

获取为JS文件传递的参数 晴

yaiba , 13:17 , 技术运用 , 评论(0) , 引用(0) , 阅读(739) , Via 本站原创
如何获取传递给js文件的参数?
今天遇到了这个问题,很愁人,
本来以为没什么的,却突然发现如此的棘手,
于是GOOGLE IT,,在某位大侠的blog中发现了一些线索,,,

解决思路:
1、首先获取到当前JS文件的SRC属性,这里有一个小技巧:我们只需要获取当前页面最后一个script标记内容即可。
为什么??因为JS是顺序解析的,当前JS脚本解析时后面的js都还没有解析到,当然就认为自己就是最后一个script了。

此外,这样获取还有一个好处:我们可以多次引用同一个JS文件且传入不同的参数,这样可以在js文件中根据参数不同做不同处理,很巧妙吧!简直就是动态语言了。
var scripts=document.getElementsByTagName("script");
var curJS=scripts[scripts.length-1];   //curJS就是我们当前的js文件

得到这个就好办了,通过curJS.src即可获取到完整的路径内容(包括参数)。

2、下面的就是解析参数内容了,解析的过程相当简单,相信很多人都容易完成这一步。
但我们要对一个特殊情况进行处理:如果一个参数被传入了多次,则要将该参数值转换为数组存储每一个传入的值。

完整测试脚本如下:可将其保存为test.js
var getArgs=(function(){
    var sc=document.getElementsByTagName('script');
    var paramsArr=sc[sc.length-1].src.split('?')[1].split('&');
    var args={},argsStr=[],param,t,name,value;
    for(var ii=0,len=paramsArr.length;ii<len;ii++){
            param=paramsArr[ii].split('=');
            name=param[0],value=param[1];
            if(typeof args[name]=="undefined"){ //参数尚不存在
                args[name]=value;
            }else if(typeof args[name]=="string"){ //参数已经存在则保存为数组
                args[name]=[args[name]]
                args[name].push(value);
            }else{  //已经是数组的
                args[name].push(value);
            }
    }
    /*在实际应用中下面的showArg和args.toString可以删掉,这里只是为了测试函数getArgs返回的内容*/
    var showArg=function(x){   //转换不同数据的显示方式
        if(typeof(x)=="string"&&!/\d+/.test(x)) return "'"+x+"'";   //字符串
        if(x instanceof Array) return "["+x+"]" //数组
        return x;   //数字
    }
    //组装成json格式
    args.toString=function(){
        for(var ii in args) argsStr.push(ii+':'+showArg(args[ii]));
        return '{'+argsStr.join(',')+'}';
    }
    return function(){return args;} //以json格式返回获取的所有参数
})();

alert(getArgs());
alert("username:"+getArgs()["username"]);


测试示例的HTML源码:保存成什么随便你了
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitiona...
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title> new document </title>
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
  <script type="text/javascript" src="test.js?id=4&username=yemoo&id=1&uid=110"></script>
  <script type="text/javascript" src="test.js?id=5&username=ajaxbbs&id=7&uid=253"></script>
  <script type="text/javascript" src="test.js?id=6&username=jack&id=8&uid=258"></script>
</head>
<body>
</body>
</html>
Tags: ,
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]