简体   繁体   English

使用不同的变量值多次在外部javascript文件中执行$(document).ready()中的代码

[英]execute code in $(document).ready() in external javascript file multiple times with different variable values

How can I run one external javascript file, which executes code on $(document).ready() event, multiple times, each time with different value of its own local variables? 如何运行一个外部javascript文件,该文件在$(document).ready()事件上多次执行代码,每次使用其自己的局部变量的值不同?

Since code in the $(document).ready() event is executed when the DOM is fully loaded, following code alerts "bar" twice. 由于$(document).ready()事件中的代码是在DOM完全加载后执行的,因此以下代码两次警告“ bar”。

external_script.js: external_script.js:

$(document).ready(function(){
    var local_var = global_var;
    alert( local_var );
});

index.html: index.html的:

<script>global_var = "foo";</script>
<script src="external_script.js"></script>

<script>global_var = "bar";</script>
<script src="external_script.js"></script>

Can I achieve that on second calling of the external_script.js it will alert a different value? 我能否在第二次调用external_script.js时实现该功能,将发出不同的值?

You are attempting an ugly side-effect hack using a global variable. 您正在尝试使用全局变量进行丑陋的副作用破解。 Please, please fix your code to be a function that accepts an argument that you can just call twice with different arguments when the document is ready. 请将代码修改为一个接受参数的函数,当文档准备就绪时,您可以使用不同的参数调用两次。

Thanks, that is exactly what I needed. 谢谢,这正是我所需要的。 Now my code looks like this: 现在我的代码如下:

external_script.js: external_script.js:

function do_stuff( local_var ) {
    alert( local_var );
}

index.html: index.html的:

<script src="external_script.js"></script>
<script>
    $(document).ready(function(){
        do_stuff( "foo" );
        do_stuff( "bar" );
    });
</script>

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

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