JavaScript的可扩展和可折叠树

时间:2014-01-26 19:24:54

标签: javascript jquery json javascript-events tree

我需要一些帮助,通过单击以下JavaScript树来创建可扩展和可折叠操作。因此,如果我点击“项目”,“沙漠”,“蔬菜”等等,它将像树一样膨胀和坍塌。所有这些都需要用JavaScript完成。[在此输入链接描述] [1]

var dataSource = ({
    "Items": ({
        "Deserts": ({}),
            "Veg": ({
            "VegPulao": "Veg Pulao",
                "PalakPaneer": "Palak Paneer",
                "PaneerButterMasala": "Paneer Butter Masala"
        }),

            "Chicken": ({
            "Tandoori": "Tandoori special"
        }),
            "Hot drinks": ({
            "Coffe": ({
                "Hot": "Hot Coffe",
                "Medium": "Medium",
                "Others": ({
                    "Iris": "Iris Coffe",
                    "Capuccino": "Capuccino"
                })
            }),
                "Tea": ({
                "Red": "Red Tea",
                "Black": "Black Tea"
            }),
                "BadamMilk": "Hot Badam Milk",
                "Bornvita": "Hot Bornvita",
                "Milk": "Hot Milk"
        }),
            "Juice": ({
            "Mango": "Mango",
                "Berry": "Berry",
                "Grapes": "Grapes",
                "Wine": ({
                "Rose": "Rose",
                    "Red wine": "Red",
                    "Apple": "Apple",
                    "Hard drinks": ({
                    "Royal challenge": "Royal challenge",
                        "Blender's Pride": "Blender's Pride"
                })
            })
        })

    })
});

function output(str, level) {
    var obj = document.getElementById("dvList1"),
        div = document.createElement("div"),
        imgTag = document.createElement("img"),
        node = document.createTextNode(str);
    imgTag.src = "Treelist/Images/minusFolder.JPG";
    div.appendChild(imgTag);
    div.style.marginLeft = (level * 20) + "px";
    div.style.marginBottom = (2) + "px";
    div.appendChild(node);
    obj.appendChild(div);
}

function output1(str, level) {
    var obj = document.getElementById("dvList1"),
        div = document.createElement("div"),
        imgTag = document.createElement("img"),
        node = document.createTextNode(str);
    imgTag.src = "Treelist/Images/Folder.JPG";
    div.appendChild(imgTag);
    div.style.marginLeft = (level * 20) + "px";
    div.style.marginBottom = (2) + "px";
    div.appendChild(node);
    obj.appendChild(div);
}

function traverseObject(obj, level) {
    for (var prop in obj) {
        if (typeof obj[prop] === "object") {
            output(prop, level);
            traverseObject(obj[prop], level + 1);
        } else {
            output(prop, level);
            output1(obj[prop], level + 1);
        }
    }
}
traverseObject(dataSource, 0);

0 个答案:

没有答案