将参数传递给 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2190801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:10:25  来源:igfitidea点击:

Passing parameters to JavaScript files

javascriptparameter-passing

提问by RaduM

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

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

So the code is something like this:

所以代码是这样的:

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

But what I want to do is:

但我想做的是:

<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();

And then search for my values.

然后搜索我的价值观。

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

我想知道是否有另一种方法可以在不构建函数来解析我的字符串的情况下做到这一点。

Do you all know other methods?

大家知道其他方法吗?

回答by Naeem Sarfraz

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

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

This code belongs in file.js:

此代码属于 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]);
        }
    };
}());

And in your html file:

在你的 html 文件中:

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

回答by Vlado

You can pass parameters with arbitrary attributes. This works in all recent browsers.

您可以传递具有任意属性的参数。这适用于所有最近的浏览器。

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

Inside somefile.js you can get passed variables values this way:

在 somefile.js 中,您可以通过以下方式获取传递的变量值:

........

…………

var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..

var my_var_1 = this_js_script.attr('data-my_var_1');   
if (typeof my_var_1 === "undefined" ) {
   var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value

var my_var_2 = this_js_script.attr('data-my_var_2');   
if (typeof my_var_2 === "undefined" ) {
   var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value

...etc...

...等等...

回答by Nalini Wanjale

Another idea I came across was assigning an idto the <script>element and passing the arguments as data-*attributes. The resulting <script>tag would look something like this:

我遇到的另一个想法是id<script>元素分配一个并将参数作为data-*属性传递。结果<script>标签看起来像这样:

<script id="helper" data-name="helper" src="helper.js"></script>

The script could then use the id to programmatically locate itself and parse the arguments. Given the previous <script>tag, the name could be retrieved like this:

然后脚本可以使用 id 以编程方式定位自身并解析参数。给定前一个<script>标签,可以像这样检索名称:

var name = document.getElementById("helper").getAttribute("data-name");

We get name= helper

我们得到name=helper

回答by user378221

Check out this URL. It is working perfectly for the requirement.

看看这个网址。它完全符合要求。

http://feather.elektrum.org/book/src.html

http://feather.elektrum.org/book/src.html

Thanks a lot to the author. For quick reference I pasted the main logic below:

非常感谢作者。为了快速参考,我粘贴了以下主要逻辑:

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

var queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery( queryString );

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;
}

回答by NawaMan

You use Global variables :-D.

您使用全局变量:-D。

Like this:

像这样:

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

The JavaScript code in 'file.js' can access to obj1and obj2without problem.

'file.js' 中的 JavaScript 代码可以访问obj1并且obj2没有问题。

EDITJust want to add that if 'file.js' wants to check if obj1and obj2have even been declared you can use the following function.

编辑只想补充一点,如果“file.js”想要检查是否obj1并且obj2甚至已经声明,您可以使用以下函数。

function IsDefined($Name) {
    return (window[$Name] != undefined);
}

Hope this helps.

希望这可以帮助。

回答by Anthony

Here is a very rushed proof of concept.

这是一个非常仓促的概念证明。

I'm sure there are at least 2 places where there can be improvements, and I'm also sure that this would not survive long in the wild. Any feedback to make it more presentable or usable is welcome.

我确信至少有两个地方可以改进,而且我也确信这不会在野外生存很长时间。欢迎任何反馈以使其更易于展示或使用。

The key is setting an id for your script element. The only catch is that this means you can only call the script once since it looks for that ID to pull the query string. This could be fixed if, instead, the script loops through all query elements to see if any of them point to it, and if so, uses the last instance of such an script element. Anyway, on with the code:

关键是为您的脚本元素设置一个 id。唯一的问题是,这意味着您只能调用脚本一次,因为它会查找该 ID 以提取查询字符串。相反,如果脚本循环遍历所有查询元素以查看它们中是否有任何指向它,并且如果是,则使用此类脚本元素的最后一个实例,则可以修复此问题。无论如何,继续使用代码:

Script being called:

被调用的脚本:

window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;

//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");

//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);

//Next split the querystring into array
var params = queryString.split("&");

//Next loop through params
for(var i = 0; i < params.length; i++){
 var name  = params[i].substring(0,params[i].indexOf("="));
 var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);

    //Test if value is a number. If not, wrap value with quotes:
    if(isNaN(parseInt(value))) {
  params[i] = params[i].replace(value, "'" + value + "'");
 }

    // Finally, use eval to set values of pre-defined variables:
 eval(params[i]);
}

//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};

Script called via following page:

通过以下页面调用的脚本:

<script id="myScript" type="text/javascript" 
        src="test.js?header=Test Page&text=This Works"></script>

<h1 id="docTitle"></h1>
<p id="docText"></p>

回答by Tofeeq

might be very simple

可能很简单

for example

例如

<script src="js/myscript.js?id=123"></script>
<script>
    var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>

You can then convert query string into json like below

然后,您可以将查询字符串转换为 json,如下所示

var json = $.parseJSON('{"' 
            + queryString.replace(/&/g, '","').replace(/=/g, '":"') 
            + '"}');

and then can use like

然后可以使用像

console.log(json.id);

回答by GeekTantra

This can be easily done if you are using some Javascript framework like jQuery. Like so,

如果您使用一些 Javascript 框架(如 jQuery),这可以轻松完成。像这样,

var x = $('script:first').attr('src'); //Fetch the source in the first script tag
var params = x.split('?')[1]; //Get the params

Now you can use these params by splitting as your variable parameters.

现在您可以通过拆分为可变参数来使用这些参数。

The same process can be done without any framework but will take some more lines of code.

同样的过程可以在没有任何框架的情况下完成,但需要更多的代码行。

回答by aefxx

Well, you could have the javascript file being built by any of the scripting languages, injecting your variables into the file on every request. You would have to tell your webserver to not dish out js-files statically (using mod_rewrite would suffice).

好吧,您可以让任何脚本语言构建 javascript 文件,在每次请求时将您的变量注入文件中。您必须告诉您的网络服务器不要静态地分发 js 文件(使用 mod_rewrite 就足够了)。

Be aware though that you lose any caching of these js-files as they are altered constantly.

但是请注意,由于这些 js 文件不断被更改,因此您会丢失对这些 js 文件的任何缓存。

Bye.

再见。

回答by dzida

Nice question and creative answers but my suggetion is to make your methods paramterized and that should solve all your problems without any tricks.

很好的问题和创造性的答案,但我的建议是让你的方法参数化,这应该可以解决你所有的问题而没有任何技巧。

if you have function:

如果你有功能:

function A()
{
    var val = external_value_from_query_string_or_global_param;
}

you can change this to:

您可以将其更改为:

function B(function_param)
{
    var val = function_param;
}

I think this is most natural approach, you don't need to crate extra documentation about 'file parameters' and you receive the same. This specially useful if you allow other developers to use your js file.

我认为这是最自然的方法,您不需要创建关于“文件参数”的额外文档,并且您会收到相同的文档。如果您允许其他开发人员使用您的 js 文件,这将特别有用。