问题:
我有以下脚本,基本上,我从 ajax 调用中获取数据,将数据传递给函数,将数据中的 id 存储在全局变量中,因此全局变量可以用于从 jQuery 检索的不同脚本中$.getScript()
:
脚本(script1.js):
该位只是通过 ajax(未显示)获取了一些数据,但它已经存在widget_data.d
,它应该getWidgetContent()
根据 in 中的数据长度运行函数widget_data.d
,在本例中为 3 次迭代:
window.global_widget_id = "";
for ( j = 0; j <= widget_data.d.length - 1; j++ ) {
getWidgetContent( widget_data.d[j] );
}
这是上面循环运行的函数:
function getWidgetContent( widget ) {
if(widget.script!=null){
window.global_widget_id = widget.widget_id;
$.getScript( "js/script2.js", function() {
alert( "direct title variable in script1.js: " + widget.title );
alert( "global variable in script1.js: " + window.global_widget_id );
alert( "direct variable in script1.js: " + widget.widget_id );
$( ".widget_header_title_" + widget.widget_id ).append( widget.title );
});
}
}
脚本(script2.js):
这是上面函数也传递全局变量的脚本,然后它应该根据全局存储的 id 通过 ajax 获取数据。
var my_widget_id = window.global_widget_id;
alert( "global variable in script2.js " + window.global_widget_id );
alert( "direct variable in script2.js: " + my_widget_id );
// then do some more ajax stuff with global_widget_id before repeating the loop again.
实际结果:
global variable in script2.js: 66
direct variable in script2.js: 66
direct title variable in script1.js: title for 57 goes here
global variable in script1.js 66
direct variable in script1.js 57
global variable in script2.js: 66
direct variable in script2.js: 66
direct title variable in script1.js: title for 65 goes here
global variable in script1.js 66
direct variable in script1.js 65
global variable in script2.js: 66
direct variable in script2.js: 66
direct title variable in script1.js: title for 66 goes here
global variable in script1.js 66
direct variable in script1.js: 66
预期成绩:
global variable in script2.js: 57
direct variable in script2.js: 57
direct title variable in script1.js: title for 57 goes here
global variable in script1.js 57
direct variable in script1.js 57
global variable in script2.js: 65
direct variable in script2.js: 65
direct title variable in script1.js: title for 65 goes here
global variable in script1.js 65
direct variable in script1.js 65
global variable in script2.js: 66
direct variable in script2.js: 66
direct title variable in script1.js: title for 66 goes here
global variable in script1.js 66
direct variable in script1.js: 66
我试过的:
基于这个网站,我可以创建一个generator function
. 这是一个模板:
(function(variable) {
return function() {
// do something with variable
}
})(value);
我试过使用它,但没有任何反应,没有错误,没有警报,没有,即:
for ( j = 0; j <= widget_data.d.length - 1; j++ ) {
var the_data = widget_data.d[j];
(function(the_data ) {
return function() {
getWidgetContent( the_data );
}
})(the_data);
}
问题:
为什么生成器功能不起作用?