Uncaught TypeError: Cannot read property 'init

2019-03-06 12:18发布

问题:

I got problem with using zTree library. this is my code

<script type="text/javascript" src="<?php echo base_url()?>asset/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="<?php echo base_url()?>asset/js/jquery.ztree.core-3.5.js"></script>
<SCRIPT type="text/javascript">
    <!--
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        }
    };

    var zNodes =[
        { id:1, pId:0, name:"Custom Icon 01", open:true, iconOpen:"<?php echo base_url()?>asset/img/diy/1_open.png", iconClose:"<?php echo base_url()?>asset/img/diy/1_close.png"},
        { id:11, pId:1, name:"leaf node 01", icon:"<?php echo base_url()?>asset/img/diy/2.png"},
        { id:12, pId:1, name:"leaf node 02", icon:"<?php echo base_url()?>asset/img/diy/2.png"},
        { id:13, pId:1, name:"leaf node 03", icon:"<?php echo base_url()?>asset/img/diy/2.png"},
        { id:2, pId:0, name:"Custom Icon 02", open:true, iconOpen:"<?php echo base_url()?>asset/img/diy/1_open.png", iconClose:"<?php echo base_url()?>asset/img/diy/1_close.png"},
        { id:21, pId:2, name:"leaf node 01", icon:"<?php echo base_url()?>asset/img/diy/8.png"},
        { id:22, pId:2, name:"leaf node 02", icon:"<?php echo base_url()?>asset/img/diy/8.png"},
        { id:23, pId:2, name:"leaf node 03", icon:"<?php echo base_url()?>asset/img/diy/8.png"}

    ];

    $(document).ready(function(){
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    });
    //-->
</SCRIPT>

and I get some error like

Uncaught TypeError: Cannot read property 'init' of undefined (anonymous function) b.extend.ready u

please help me, how can I resolve this problem? thanks

回答1:

This happens because of including js at multiple places. I have encountered the same issue in my Portal page where jquery-1.4.4.min.js and jquery.ztree.core-3.5.js were included many places.

I fixed this issue by removing all references to js from all the portlets on that page and added these js globally in theme/_diff/portal_noraml.vm in the given order.



回答2:

This error's in your $(document).ready(), and it's because your zTree script hasn't been loaded correctly. "Cannot read property 'init' of undefined" means you wrote something that evaluates as undefined.init - so you know that $.fn.zTree is undefined.

If you check the network tab of your browser's developer tools, you should hopefully see the problem. I'd guess it'll either be a 404 (ie. the src attribute of the <script> tag is incorrect) or a 403 (ie. you need to change the permissions on your zTree file so the web server can read it).