从另一个js源文件调用函数时出现未定义的错误

Ric*_*ard 0 javascript version-control jquery

我有一个问题涉及调用另一个js源文件中的函数.

我使用调用该特定函数的函数在文件之前声明了源文件.我认为这会起作用,但它会给出一个未定义的错误.

我还在一个文件中有一个函数,该文件在稍后声明的源文件中调用函数.这将涉及相同的文件,但反过来.

函数在文档就绪语句(函数)之间声明.

有没有办法避免未定义的错误?

这是我如何设置它:

<script type="text/javascript" src="includes/livetabs.js"></script>
<script type="text/javascript" src="includes/chat.js"></script>


//this is in the chat.js file
$(document).ready(function(){

function chatWith(chatuser) {
    check=iscookieUsername();
    if (!check){
            chatusersuspended=chatuser;
            showchatinlogform();
    }
    createChatBox(chatuser);
    $("#chatbox_"+chatuser+" .chatboxtextarea").focus();
}


});

//this is in the livetabs.js file
$(document).ready(function(){

function iscookieUsername(){
        if (!tbusername){

            return false;
        }
        if (issessionusername){//flag if session has already been set

            return true;
        }
        $.ajax({
            url: "includes/livetabs.php", 
            data: ({username: tbusername, action: "setsessionusername"}),
            cache: false,
            type: "POST",
            dataType: "json",
            success: function(data) {
            //store username in php session
            //some personal user preferences returned 
            usernamecookie=data.cookie;
            trackuser=data.track;
            issessionusername=1;
        }});

        return true;
    }

});
Run Code Online (Sandbox Code Playgroud)

谢谢,理查德

Sol*_*ogi 7

如果您已在$(document).ready方法调用中定义了函数,则它们将无法从外部显示.尝试在ready方法调用之外定义它们.

$(document).ready(
    function()
    {
        var test = function() { alert('test'); };

        test(); //It will work here.

        anotherTest(); //This will also work.

    }

);

function anotherTest() { alert('anotherTest'); };

test(); //You can't call test function here because test is defined inside the anonymous function passed to the 'ready' method.

anotherTest(); // Alerts 'anotherTest'. 
Run Code Online (Sandbox Code Playgroud)

如果这不是您的代码的布局方式,请发布您的源代码,以便能够识别问题.