【问题标题】:undefined error when calling function from another js sourcefile从另一个 js 源文件调用函数时出现未定义错误
【发布时间】:2009-07-07 01:25:33
【问题描述】:

我有一个关于在另一个 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;
    }

});

谢谢,理查德

【问题讨论】:

  • 可以发一些 HTML/JS 源代码吗?
  • 好的,等一下。如果还不够,我会给出该网站的链接

标签: javascript jquery version-control


【解决方案1】:

如果您在 $(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'. 

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

【讨论】:

  • 谢谢,我编辑了我原来的问题。正如你所建议的。我必须将它们从文档准备方法中取出。那就这样吧。
  • Richard,把 'iscookieUsername' 和 'chatWith' 函数放到文档之外准备好了。 document.ready 是您放置网页加载后要运行的代码的地方。你没有在那里定义你的功能。请尝试阅读一些 jQuery 教程以了解更多信息。
【解决方案2】:

您的第一个源文件,即包含您要调用的函数的文件,可能存在语法错误,导致该函数无法使用。

此外,加载文件的顺序无关紧要,该功能始终可用。示例:

function foo() { alert('foo!'); }
foo();
bar();
function bar() { alert('bar!'); }

编辑:看起来 SolutionYogi 预测了正确的答案。但是作为参考,我会留下我的。

【讨论】:

  • 像@SOLUTION YOGI 建议的那样,很可能是由包含函数的文档准备方法引起的。我得先检查一下。
  • 这是我的案例:结束了一个小时的调查!
【解决方案3】:

在浏览特定页面之前,请使用 google chrome 并按 F12 以查看开发者工具。 在网络中,您可以查看加载了哪些文件,搜索包含您的函数的脚本。 . (您也可以过滤脚本)它应该在顶部,并且您的调用脚本应该稍后加载。如果未加载,则早先将该文件包含在您的页面中。希望能解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多