是否可以将变量发送到使用 $.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.
}
关于jquery - 将变量发送到 $.getScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396100/