jquery - 将变量发送到 $.getScript

标签 jquery getscript

是否可以将变量发送到使用 $.getScript 加载的脚本?

目前我有:

$.getScript( "js/my_script.js", function() {
// do something here after script has loaded
});

但我想向加载的脚本发送一个变量。这可能吗?如果可以,如何实现?

例如

// this is a variable set outside of the script loaded via `$.getScript`
var my_variable = 1

// how do I get that variable sent to `my_script.js`
$.getScript( "my_script.js", function() {
// do something here after script has loaded
});

最佳答案

jQuery.getScript():

The script is executed in the global context, so it can refer to other variables and use jQuery functions.

从文档来看,您的变量应该可以在$.getScript(function(){..})调用中访问。因此,这可能是范围的问题。您的变量 my_variable 存在(大概)在 $(document).ready(function(){...}) 内,因此仅限于该特定范围。

尝试通过将数据分配给窗口对象来使用全局变量:

// Set it as a global variable by assigning it to the window object
window.my_variable = 'some value';

// Now use it inside of $.getScript()
$.getScript( "my_script.js", function() {
  // Access it by name
  alert(my_variable);
  // or as a property of window
  alert(window.my_variable);
  // both ways to access my_variable work and are valid.
}

来源:老问题here和 $.getScript 文档 here .
在我的个人服务器上验证。

关于jquery - 将变量发送到 $.getScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396100/

相关文章:

javascript - 使用图像代替 Canvas

javascript - 仅当使用 jQuery 加载我的所有 JavaScript 时执行某些操作的最佳方式是什么?

javascript - 在网络应用程序中缓存所有脚本

javascript - 难以使用全局变量和 $.getScript

javascript - 检测脚本是否已经加载

jQuery 检测连续的鼠标按下

javascript - 自动将指标添加到 bootstrap carousel

javascript - 为什么需要将 $(document).ready 添加到自执行函数中?

jquery - 数组删除\t\n。 --NodeJS--