self-calling function inside jQuery plugin

独自空忆成欢 提交于 2019-12-12 03:35:40

问题


I am generating a tree (nested UL list) with javascript using the self-calling function below. I might add that it is within a jQuery plugin, if that is at all relevant to the issue (perhaps it might be?).

The variable gd contains a json/array sniffed from a filestructure, so it's basically folders and images's names, and some more data (like the self-explainatory isFolder attribute etc.)

        for (i = 0; i < gd.length; ++i) {

is interrupted by the self-call.

    var drawTree = function(self,parent){

        var gd = self.data('galleryData');

        self.data('sidebar', self.data('sidebar')+'<ul>');

        for (i = 0; i < gd.length; ++i) {

            console.log('looping '+i+': '+gd[i]['name']+', isFolder: '+gd[i]['isFolder']+', parent: '+gd[i]['parent']);

            if ( (gd[i]['isFolder'] == true) && (gd[i]['parent'] == parent) ) {
                console.error(gd[i]['name']);
                self.data('sidebar', self.data('sidebar')+'<li data-folder="'+gd[i]['fileId']+'" class="folderLink">');
                self.data('sidebar', self.data('sidebar')+gd[i]['name']);

                self.data('drawTree')(self,gd[i]['fileId']); // <-- The line causing trouble

                self.data('sidebar', self.data('sidebar')+'</li>');
            }
        }

        self.data('sidebar', self.data('sidebar')+'</ul>');

    };
    this.data('drawTree',drawTree);

My problem is that if I leave out the "problem" line

self.data('drawTree')(self,gd[i]['fileId']);

Which is the one making the self-call (which enables me to also list sub-folders) then I get a neat list of all the "level 0" folders (those without a parent, or parent attribute set to an empty string). But then I will of course not get any of the nested folders.

Root
    actions
    appz
    categoriez
    david
    devices
    mimetypes
    places
    space
    status

If I do include the self-call, I get all nested levels, but only for the very first of the folders at "level 0", as if the main loop (this line from the code above)

Root
    actions
        actionsSub1
            actionSub2
                actionSub3
                    actionSub4

回答1:


You have a global variable. Do not treat var is as optional.

for (i = 0; i < gd.length; ++i) {  <-- i is global

now the other function call will not change it when you place var in front of i.

for (var i = 0; i < gd.length; ++i) {


来源:https://stackoverflow.com/questions/29561480/self-calling-function-inside-jquery-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!