简体   繁体   English

将参数传递给文档就绪的.js文件

[英]Pass parameters to .js file on document ready

I have seen several people ask parts of this question and tried the various solutions but nothing seems to work. 我已经看到几个人问了这个问题的一部分,并尝试了各种解决方案,但似乎没有任何效果。 I'm not sure if it's the combination or something else in my project that is causing it to not work. 我不确定是组合还是项目中的其他原因导致其无效。

In my project I have various pages that display similar DataTables. 在我的项目中,我有多个页面显示相似的数据表。 I'm wanting to put the initialisation of these tables in one file to save duplication. 我想将这些表的初始化放在一个文件中以节省重复。 But I would like to pass in parameters to account for the minor differences between eg column headers. 但是我想传入参数以解决例如列标题之间的细微差别。 Just to complicate it the initialisation is unsurprisingly done on document.ready. 只是使其复杂化,对document.ready进行初始化就不足为奇了。

Things I have tried: 我尝试过的事情:
Pass vars to JavaScript via the SRC attribute 通过SRC属性将var传递给JavaScript
http://feather.elektrum.org/book/src.html http://feather.elektrum.org/book/src.html

In the code example below I never hit the second alert. 在下面的代码示例中,我从未遇到第二个警报。 What I want if for it to hit the second and third alerts and for the contents of test_var to be correct: 我想要的是它能击中第二个和第三个警报,并且test_var的内容正确:

(cs)html file (cs)html文件

<script>
    $(document).ready(function () {
        var test_var = "Hopefully this has worked";
        alert("Pre TestScript");
        $.getScript("TestScript.js"); // Tried different paths to the file here as well
    });
</script>

TestScript.js TestScript.js

alert("In the TestScript");
alert("Test variable is: " + test_var);

Perhaps I'm going about it all wrong and there is a different/simpler way to achieve the passing of parameters to a script (file) during document.ready 也许我正在解决所有错误,并且在document.ready期间有一种不同/更简单的方法来实现将参数传递到脚本(文件)的功能

A simplest way to do it would be (Assuming that variable name test_var is not a global variable or built-in property/method already) 最简单的方法是(假设变量名test_var不是全局变量或内置属性/方法)

<script>
    $(document).ready(function () {
        var test_var = "Hopefully this has worked";
        alert("Pre TestScript");
        window.test_var = "Hopefully this has worked";
        $.getScript("TestScript.js"); // Tried different paths to the file here as well
    });
</script>

Above I assumed that test_var will be defined inside document.ready only. 上面我假设test_var仅在document.ready内部定义。 Otherwise, if it was a global variable, then it can be accessed without window . 否则,如果它是全局变量,则可以不使用window对其进行访问。

And in your TestScript.js , simply delete the variable after it has been consumed 在您的TestScript.js中,只需在使用完变量后删除该变量

alert("In the TestScript");
alert("Test variable is: " + test_var);
delete window.test_var;
$(document).ready(function () {
    test_var = "Hopefully this has worked";
    $.getScript("TestScript.js"); // Tried different paths to the file here as well
});

Unfortunately you cannot pass parameters to a JS file through the URL as the request to retrieve the file is not available from within JS code. 不幸的是,您无法通过URL将参数传递给JS文件,因为JS代码中没有检索文件的请求。

Instead you can declare variables before you include the JS file in the page which can then be read in it, something like this: 相反,您可以在将JS文件包含在页面中之前声明变量,然后可以在其中读取它,如下所示:

foo.html foo.html

<script>
    var test_var = "Hopefully this has worked";
</script>
<script src="testscript.js"></script>

testscript.js testscript.js

console.log(test_var); // = "Hopefully this has worked"

You need to wrap your code in a function: 您需要将代码包装在一个函数中:

function testScript(test_var) {
    alert("In the TestScript");
    alert("Test variable is: " + test_var);
}

And then you can use it like this: 然后您可以像这样使用它:

<script>
    $(document).ready(function () {
        var test_var = "Hopefully this has worked";
        alert("Pre TestScript");
        $('<script>')
            .attr('type', 'text/javascript')
            .attr('href', 'TestScript.js')
            .appendTo('head');
        testScript(test_var);
    });
</script>

I think this should solve your problem. 我认为这应该可以解决您的问题。 Include the TestScript.js in the html page. 在HTML页面中包含TestScript.js。

(cs)html file (cs)html文件

<script>
    $(document).ready(function () {
        var test_var = "Hopefully this has worked";
        alert("Pre TestScript");
        executeCommonScript();
    });
</script>

TestScript.js TestScript.js

function executeCommonScript(){
   alert("In the TestScript");
   alert("Test variable is: " + test_var);
}

In addition to the other great solutions that have been proposed so far, a different option is to put the variables you need defined somehow in your HTML, eg as data-attributes, 除了迄今为止已提出的其他出色解决方案外,另一种选择是将您需要定义的变量以某种方式放入HTML中,例如作为数据属性,

Since you're using jQuery anyway something like this would work: 由于您无论如何都在使用jQuery,因此这样的方法会起作用:

 $(document).ready(function() { var test_var = $('.data-container').data('test-var'); alert('Don\\'t be alarmed: '+test_var); }); 
 .data-container { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="data-container" data-test-var="This is just a test"></div> 

You can access these data-attributes in any file you include, so you wouldn't have to worry about passing variables back and forth. 您可以在包含的任何文件中访问这些数据属性,因此不必担心来回传递变量。

Of course this solution makes the most sense if you don't add a div just to hold your variables, but add data-attributes to those elements that will actually be affected by the variables 当然,如果您不只是为了保存变量而添加div,而是将数据属性添加到实际上将受到变量影响的那些元素上,则此解决方案最有意义

Many people correctly answered my question, thank you all. 许多人正确回答了我的问题,谢谢大家。 The problem I was having in getting it to work was that my script file that I was trying to pass parameters in to was in my Views/Shared folder which as outlined here is blocked. 我是在它让工作遇到的问题是,我试图传递到参数我的脚本文件在我的意见/共享文件夹,其作为概述这里被阻断。

Once I moved my script out of the Views folder it all worked fine. 将脚本移出Views文件夹后,一切正常。 And in addition to the above answers the simplest I found was this 而且除了上述的答案,我发现最简单的就是

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM