Home Blog Photo Community Open Source
引用js的时候带入参数,怎么获取?

How to Get Parameters When Including a Javascript File

  1. Method One
   <script src="2.js?v=123&p=445"></script>
    var urlparse;
    urlparse = document.scripts[document.scripts.length - 1].src.split("\?");

    var values = {};
    if(urlparse.length > 1){
        var parms = urlparse[1].split("&");
        for (var i = 0; i < parms.length; i++) {
            var parm = parms[i].split("=");
            values[parm[0]] = parm[1];
        }
    }

    console.log(values);

    // {v: "123", p: "445"}
  1. Method Two
<script src="word.js">
  jv.word = {
    recongnize : true,
    phoneticize: true,
    outerlink: true,
    translator: true
  }
</script>
;(function() {
  jv = {}; jv.word = {}; 
  var scripts = document.getElementsByTagName("script");
  eval(scripts[ scripts.length - 1 ].innerHTML);
  console.log(jv.word);
})();
  1. Method Three
    <script type="text/javascript" src="test.js">a=b&c=d</script>
var scripts = document.getElementsByTagName("script");
  var scriptArgs = scripts[ scripts.length - 1 ].innerHTML.replace(/[s]/g, '');
  1. Method Four
<script type="text/javascript" src="test.js" onload="TB.SomeFun('a=b&c=d')"></script>
TB = {};
 TB.SomeFun = function(arg) { //code 
};

If you use IE browser, the code might look something like the following:

if(window.ActiveXObject) { 
    var scripts = document.getElementsByTagName('script'); 
    eval(scripts[scripts.length - 1].getAttribute('onload')); 
}
  1. Method Five
<script id="testScript" type="text/javascript" src="test.js" data="a=b&c=d"></script>
var scriptArgs = document.getElementById('testScript').getAttribute('data');

or

var scripts = document.getElementsByTagName('script'); 
var currentScript = scripts[scripts.length - 1];