jQuery插件中的自调用函数 [英] self-calling function inside jQuery plugin

查看:418
本文介绍了jQuery插件中的自调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的自调用功能使用javascript生成树(嵌套的UL列表).我可能会添加它在jQuery插件中,如果与问题完全相关(也许是吗?).

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?).

变量gd包含一个从文件结构中嗅探到的json/数组,因此它基本上是文件夹和图像的名称,以及更多数据(例如不言自明的isFolder属性等)

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) {

被自通话打断.

    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']);

哪个是进行自我调用的文件(这使我也可以列出子文件夹),然后我得到了所有级别0"文件夹的整齐列表(那些没有父级或将父级属性设置为空的文件夹)细绳).但是我当然不会得到任何嵌套的文件夹.

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

如果我确实包含了自调用功能,则将获得所有嵌套级别,但仅对于"level 0"文件夹中的第一个文件夹,就好像是主循环一样(此行来自上面的代码)

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

推荐答案

您有一个全局变量.请勿将var视为可选.

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

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

现在,将var放在i前面时,另一个函数调用不会更改它.

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) {

这篇关于jQuery插件中的自调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆