外部函数未调用 - javascript

时间:2013-12-07 21:39:37

标签: javascript

谁能告诉我为什么这不起作用?

ui = (function() {
collabElement = document.getElementById( 'approveCollab' );
    if(collabElement)
        collabElement.onclick = function(){editor.collaborate(); removeOverlay();}

    deleteElement = document.getElementById( 'approveDelete' );
    if(deleteElement)
        deleteElement.onclick = function(){editor.deletePost(); removeOverlay();}
})();

“collaborate”是“editor.js”文件中的导出函数。 removeOverlay()“是同一文件中的函数。 单击“collabElement”时,仅调用“removeOverlay”。

没有错误,只是根本没有调用该函数。

这些是从editor.js调用的函数:

function collaborate( event ) {

    console.log("started");
    var url = '';

    var postID = document.querySelector('.save').getAttribute('id');
    var recipient = document.querySelector('.collab-input').value;

    //validate email syntax
    var atpos=recipient.indexOf("@");
    var dotpos=recipient.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
        console.log("wrong email");
        document.querySelector('.email-error').style.display = "block";
    }
    else{
        console.log("sending email to " + recipient);
        document.querySelector('.email-error').style.display = "none";
        if(postID != "new"){
            url = url + "?id=" + postID + "&recipient=" + recipient;

            var request = new XMLHttpRequest();
            request.open("GET", "collaborate"+url, true);
            request.send();
        }
    }
}

function deletePost( event ) {

    var url = '';

    var postID = document.querySelector('.save').getAttribute('id');
    if(postID != "new"){
        url = url + "?id=" + postID;

        var request = new XMLHttpRequest();
        request.open("GET", "delete"+url, true);
        request.send();
    }
}

2 个答案:

答案 0 :(得分:4)

如果您想调用一个函数,请添加()

editor.collaborate()

(而不只是editor.collaborate,它只会解决这个问题)

答案 1 :(得分:2)

我怀疑问题是你的IIFE没有返回任何东西; ui永远不会被定义。我想你想要这个:

ui = (function() {
    collabElement = document.getElementById( 'approveCollab' );
    if(collabElement)
        collabElement.onclick = function(){editor.collaborate; removeOverlay();}
    //return collabElement so it's assigned to ui
    return collabElement;
})();

修改

虽然你的IIFE确实没有返回任何东西,但看起来彼得的答案现在对你来说更加相关;没有召集合作。他似乎是这个问题的正确答案。