在javascript

时间:2015-05-22 10:47:25

标签: javascript jquery

在我的应用程序中,我想在初始化JavaScript时传递值,如下所示。不要使用任何标签或其他方法。

<script src="../js/carTravalling.js?uid=Bjkls&appid=1234"  type="text/javascript"></script>

如何在我的JavaScript carTravalling.js文件中获取uid和appid。 ?

2 个答案:

答案 0 :(得分:1)

你可以做这样的事情

创建一个文件,例如passArgLibrary.js

var passArgLibrary = passArgLibrary || (function(){
    var argumentObject = {};

    return {
        init : function(argumentValues) {
            argumentObject = argumentValues;
            // Add other init if needed
        },
        test : function() {
            alert('Test! -' + argumentObject[0]);
        }
    };
}());

<!-- Would usually use this first line to get the js file but i'm using dropbox for example
<script type="text/javascript" src="passArgLibrary.js"></script> -->
<script src="https://dl.dropboxusercontent.com/u/71030101/passArgLibrary.js"></script>
<script type="text/javascript">
   passArgLibrary.init(["testValue", 1, "testValueID"]);
   passArgLibrary.test();
</script>

答案 1 :(得分:0)

我在http://feather.elektrum.org/book/src.html enter link description here

的帮助下得到了答案
function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

        var scripts = document.getElementsByTagName('script');
        var myScript = scripts[0];
        var queryString = myScript.src.replace(/^[^\?]+\??/,'');
        var params = parseQuery( queryString );

        console.log(params.uid+" "+params.appid);