将参数传递给JavaScript文件 [英] Passing parameters to JavaScript files

查看:160
本文介绍了将参数传递给JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常会有一个我想要使用的JavaScript文件,需要在我的网页中定义某些变量。

Often I will have a JavaScript file that I want to use which requires certain variables be defined in my web page.

所以代码是这样的:

<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
   var obj1 = "somevalue";
</script>

但我想做的是:

<script type="text/javascript" 
     src="file.js?obj1=somevalue&obj2=someothervalue"></script>

我尝试了不同的方法,最好的方法是解析查询字符串,如下所示:

I tried different methods and the best one yet is to parse the query string like this:

var scriptSrc = document.getElementById("myscript").src.toLowerCase();

然后搜索我的价值。

我想知道是否有另一种方法可以在不构建解析我的字符串的函数的情况下执行此操作。

I wonder if there is another way to do this without building a function to parse my string.

你们都知道其他方法吗?

Do you all know other methods?

推荐答案

如果可能,我建议不要使用全局变量。使用命名空间和OOP将参数传递给对象。

I'd recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.

此代码属于file.js:

This code belongs in file.js:

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function() {
            alert('Hello World! -' + _args[0]);
        }
    };
}());

在你的html文件中:

And in your html file:

<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
   MYLIBRARY.init(["somevalue", 1, "controlId"]);
   MYLIBRARY.helloWorld();
</script>

这篇关于将参数传递给JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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