未捕获的ReferenceError: - 未定义变量(递归调用)

时间:2017-07-22 09:56:33

标签: javascript

我遇到了问题

Uncaught ReferenceError: fg_my_content is not defined
    at flipGallery (flipgallery.min.js:53)
    at asdfg (Albumfinal.php:420)
    at onload (Albumfinal.php:21)

这是我的代码

<body onload="loadContent()">
.
.
.
.
    <!-- DOM area must be loaded before executing scripts-->
    <!-- /DOM area must be loaded before executing scripts-->
    <script>
        function loadContent(){
            var fg_my_content1 = <?= json_encode($fg_my_content)?>;
            var fg_my_content2 = <?= json_encode($fg_my_content2)?>;
            var fg_my_content=fg_my_content1;
            flipGallery();
            fg_my_content=fg_my_content2;
            flipGallery2();
        }
    </script>
    <script type="text/javascript" src="flipgallery/flipgallery.min.js"></script><!-- has a function that uses variable fg_my_content -->
    <script type="text/javascript" src="flipgallery2/flipgallery.min.js"></script><!-- has a function that uses variable fg_my_content -->
</body>

json_encode($fg_my_content)的值来自php

{
"user":{
        "name": "something",
        "age": 20,
        "phonenumber": "321456987"
    }
}

并且使用变量fg_my_content的函数类似于

//flipgallery/flipgallery.min.js
function flipGallery(){
    .
    .
    .
    doSomethingWith(fg_my_content);
    .
    .
    .
}
//flipgallery2/flipgallery.min.js
function flipGallery2(){
    .
    .
    .
    doSomethingWith(fg_my_content);
    .
    .
    .
}

我的代码应该做的是加载html DOM,然后调用函数loadContent(),它应该声明变量fg_my_content,然后调用函数flipGallery()。但由于某种原因,变量fg_my_content未在函数flipGallery()中定义。那是为什么?

为什么变量fg_my_content未在flipGallery()内定义,即使我在调用函数之前声明它?

1 个答案:

答案 0 :(得分:0)

将fg_my_content定义为全局,如下所示:

<script>
        var fg_my_content;
        function loadContent(){
            var fg_my_content1 = <?= json_encode($fg_my_content)?>;
            var fg_my_content2 = <?= json_encode($fg_my_content2)?>;
            fg_my_content=fg_my_content1;
            flipGallery();
            fg_my_content=fg_my_content2;
            flipGallery2();
        }
</script>

或    将值fg_my_content传递给函数