Pergunta

I have a flat HTML table like this:

parent | child

item0 | item1
item1 | item2
item1 | item3

Is there a way that I can use Kendo UI TreeView to create a tree based on that table with parent and child column? If there is, how do I do that? If there isn't, what's the best recommended way of constructing a tree with an HTML table?

Foi útil?

Solução

It will be better it you can provide data-source to treeview, but if you have html table like you stated above then you have to create data-source for treeview & then bind it.

I have created sample jsfiddle for it http://jsfiddle.net/GHdwR/41/

Enjoy :)

var DataTable = $("#DataTable")
var Newdata = [];
DataTable.find("td").each(function () {
    var Text = $(this)[0].innerText;
    var item = {
        text: Text
    };
    var ParentNodeValue = FindParentNodeValue(DataTable, Text);
    if (ParentNodeValue === "" && GetItemFormText(ParentNodeValue) === undefined) {
        Newdata.push(item);
    } else {
        var InsertChildInTo = GetItemFormText(ParentNodeValue);
        var childAlreadyPresent = GetItemFormText(Text);
        if (InsertChildInTo !== undefined && childAlreadyPresent === undefined) {
            if (InsertChildInTo.items === undefined) InsertChildInTo.items = [];

            InsertChildInTo.items.push(item);
        }
    }

});

function GetItemFormText(Text) {

    var temp = undefined;
    for (var j = 0; j < Newdata.length; j++) {
        temp = GetDataItemFromChild(Text, Newdata[j]);
        if (temp !== undefined) {
            return temp;
            break;
        }
    }
}

function GetDataItemFromChild(Text, aDataItem) {
    if (aDataItem.text === Text) {
        return aDataItem;
    }

    var temp = undefined;

    if (aDataItem.items !== undefined) {
        for (var j = 0; j < aDataItem.items.length; j++) {
            temp = GetDataItemFromChild(Text, aDataItem.items[j]);
            if (temp !== undefined) {
                break;
            }
        }
    }
    return temp;
}

function FindParentNodeValue(DataTable, Text) {

    var returnVal = "";
    DataTable.find("tr").each(function () {
        var childText = $(this).find("td")[1].innerText;
        if (Text === childText) {
            returnVal = $(this).find("td")[0].innerText;
        }

    });
    return returnVal;
}

var ds = new kendo.data.HierarchicalDataSource({
    data: Newdata
});

var treeview = $("#treeview").kendoTreeView({
    dataSource: ds,
    loadOnDemand: false
}).data("kendoTreeView");

treeview.expand(".k-item");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top