$(window).load返回从外部.js文件调用时未定义的函数

时间:2013-04-18 15:07:08

标签: jquery

我实现了一个main.js外部文件:

function initialize() {
...
}

和我调用的main.php文件:

<script type="text/javascript" src="./main.js"></script>

然后我打电话给:

$(window).load(function() {
  initialize();
}

我知道window.load会在所有内容都已加载并准备就绪后触发代码。

为什么会返回ReferenceError: initialize is not defined

编辑:这是我最简单的代码:

// # main.js.php file

<?php 
session_start();
include_once("include/functions.php"); 
session_write_close();

?>

var elements = [];

var element = { 
    container: "",
    visible: false,

    init : function(div) {
    ....
    }
};

function initialize() {
    elements.push(element.initialize("mydiv")); 
}


// # main.php file
<?php
session_start();
include_once("include/functions.php"); 
include_once("include/db_engine.php"); 

session_write_close();
}
?>
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="Content-Type" content="text/html" />
    <link rel="stylesheet" type="text/css" href="./css/stile.css" media="all" />
    <script type="text/javascript" src="./js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="./main.js.php"></script>

    <script type="text/javascript"> 

        $(window).load(function() {
              initialize();
        });

    </script>
</head>
<body>
    <div id="mydiv"></div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

var elements = [];

var element = { 
    container: "",
    visible: false,

    init : function(div) {
    //...
       return 'hello world';
    }
};

function initialize() {
    elements.push(element.init("mydiv")); //was a typing error 
}

您的对象定义和function initialize()仅将["hello world"]推送到elements或推送的函数,整个var element= {...}对象。< / p>

和其他锻炼

    $(window).load(function() {
        //initialize();
        console.log('window call');
    });
    $(document).ready(function() {
        //initialize();
        console.log('document call');
    });

火灾..

优先: 'document call' 秒: 'window call'

答案 1 :(得分:-1)

我自己解决了..这是一个错误的回应来自cookie的一些PHP变量...感谢所有人:-) BTW:它只是调用函数init(){...}