当我从不同的文件中调用对象时,我遇到了问题。
function node(id, content, prev, next){
this.id = id;
this.prev = prev;
this.next = next;
this.content = content;
}
我正在使用此代码加载外部文件,以防以前未定义该对象。
function callNode(node){
if(typeof(node) === 'undefined')
{
path = "js/tree/t2.js";
$.getScript(path, function(){
console.log('done');
for(i in node)
alert(node[i]);
});
}
else alert('node exist');
}
在t2.js中我有以下内容:
n1 = new node('text1','n1');
n2 = new node('text2','n2');
n3 = new node('text3','n3');
n2.next = n3;
n2.prev = n1;
html代码:
<button onclick="callNode(n2)"..
但它一直给我未定义的对象
答案 0 :(得分:1)
如果callNode(n2)
尚未初始化,则无法致电n2
。您需要先加载脚本,然后才能访问n2
- 例如从回调中访问。
// init.js
function Node(id, content, prev, next){
this.id = id;
this.prev = prev;
this.next = next;
this.content = content;
}
var loader;
function callNode(nodeid, callback){
if (!loader)
loader = $.getScript("js/tree/t2.js").done(function() {
console.log('done');
});
loader.done(function() {
callback(nodes[nodeid]););
}
}
function logNode(node) {
// not sure whether you really want *that*, but
for (i in node)
alert(node[i]);
});
// t2.js
nodes = {
n1: new Node('text1','n1'),
n2: new Node('text2','n2'),
n3: new Node('text3','n3')
};
nodes.n2.next = nodes.n3;
nodes.n2.prev = nodes.n1;
// event handler code:
callNode("n2", logNode);