我想在此模块中使用数组中的值填充jquery ui模式对话框:
var WsdArrays = function() {
var arr = [["the boy is going home", "wsd_aud1"],
["You and I are friends", "wsd_aud2"],
["He has a book of mine", "wsd_aud3"],
["He will run to his home", "wsd_aud4"],
... ];
return {
values: function(index1, index2) {
return arr[index1][index2];
}
};
}();
这样可以正常工作:
console.log(WsdArrays.values(0, 0));
但是在jquery语句中调用模块函数时它不起作用,因为jquery click事件生成了参数:
jQuery("span.ws_dialog_icon").on("click",function(evnt) {
jQuery("div#ws_dialog").dialog("open");
evnt.stopPropagation();
var elementId = evnt.target.id,
index1 = elementId.substr(7), //strips chars from ids like "wsd_img01"
index2 = 0,
arrayVals = WsdArrays.values(index1, index2);
jQuery("div#wsd_text").text(arrayVals);
});
这里有什么需要改变的?
答案 0 :(得分:0)
使用window
使其更加全球化。
所以设置如下:
window.WsdArrays = function() {
var arr = [["the boy is going home", "wsd_aud1"],
["You and I are friends", "wsd_aud2"],
["He has a book of mine", "wsd_aud3"],
["He will run to his home", "wsd_aud4"],
... ];
return {
values: function(index1, index2) {
return arr[index1][index2];
}
};
}();
这种方式它将位于全局命名空间中,如果它是在另一个函数中创建的,那么它也可以工作。如果在另一个函数中使用var
声明它,它将只在该函数中可用。
答案 1 :(得分:0)
我认为scoping
确实是主要问题。
但我没有乱丢window
/全局命名空间,而是建议使用另一个命名空间:
var app=function($){
var WsdArrays = function() {
var arr = [["the boy is going home", "wsd_aud1"],
["You and I are friends", "wsd_aud2"],
["He has a book of mine", "wsd_aud3"],
["He will run to his home", "wsd_aud4"],
... ];
return {
values: function(index1, index2) {
return arr[index1][index2];
}
};
}();
$("span.ws_dialog_icon").on("click",function(evnt) {
$("div#ws_dialog").dialog("open");
evnt.stopPropagation();
var elementId = evnt.target.id,
index1 = elementId.substr(7), //strips chars from ids like "wsd_img01"
index2 = 0,
arrayVals = WsdArrays.values(index1, index2);
$("div#wsd_text").text(arrayVals);
});
}(jQuery);
因此,不需要使用全局范围,并且onClick
可以看到WsdArrays。
此外:你为什么不使用字典方法?
var WsdArrays=function(){
var whatEverString={
"wsd_aud1","the boy is going home",
"wsd:auds","you and i are friends"
};
return {
values:function(id){ return whatEverString[id]; }
}
}
另一件事: 为什么要在IFFE中封装一个简单的函数?仅用于命名空间的原因? 一个简单的功能就足够了。
答案 2 :(得分:0)