0

当我从不同的文件中调用一个对象时,我遇到了一个问题。

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)"..

但它一直给我未定义的对象

4

1 回答 1

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);
于 2013-02-05T13:52:02.143 回答