如何在HTML DROPDOWN創建嵌套的JSON數據UL li元素
我原來的問題是這樣的:https://stackoverflow.com/questions/38596714/implement-dynamic-dropdown-in-select-tag-in-html
但下面是我能找到互聯網上。我想創建類似上面的東西。以下是代碼片段。它工作得很好。但我怎樣才能使它變得動態。我的意思是如果我手動添加ul和li,樹會正確渲染。但我希望按照從REST API接收到的JSON發生。如何從嵌套的JSON數據添加ul和li元素。有人可以幫幫我嗎。
工作代碼鏈接: http://jsfiddle.net/jddevight/esS4k/
工作代碼片段:
var dropdown = $("#dropdown").kendoDropDownList({
dataSource: [{ text: "", value: "" }],
dataTextField: "text",
dataValueField: "value",
open: function (e) {
// If the treeview is not visible, then make it visible.
if (!$treeviewRootElem.hasClass("k-custom-visible")) {
$treeviewRootElem.slideToggle('fast', function() {
dropdown.close();
$treeviewRootElem.addClass("k-custom-visible");
});
}
}
}).data("kendoDropDownList");
var $dropdownRootElem = $(dropdown.element).closest("span.k-dropdown");
var treeview = $("#treeview").kendoTreeView({
select: function (e) {
// When a node is selected, display the text for the node in the dropdown and hide the treeview.
$dropdownRootElem.find("span.k-input").text($(e.node).children("div").text());
$treeviewRootElem.slideToggle('fast', function() {
$treeviewRootElem.removeClass("k-custom-visible");
});
}
}).data("kendoTreeView");
var $treeviewRootElem = $(treeview.element).closest("div.k-treeview");
// Hide the treeview.
$treeviewRootElem
.width($dropdownRootElem.width())
.css({ "border":"1px solid grey", "display": "none", "position": "absolute" });
// Position the treeview so that it is below the dropdown.
$treeviewRootElem
.css({ "top": $dropdownRootElem.position().top + $dropdownRootElem.height(), "left": $dropdownRootElem.position().left });
$(document).click(function(e) {
// Ignore clicks on the treetriew.
if ($(e.target).closest("div.k-treeview").length == 0) {
// If visible, then close the treeview.
if ($treeviewRootElem.hasClass("k-custom-visible")) {
$treeviewRootElem.slideToggle('fast', function() {
$treeviewRootElem.removeClass("k-custom-visible");
});
}
}
});
HTML:
<ul id="treeview">
<li data-expanded="true">Item 1
<ul>
<li>Item 1.1</li>
<li>Item 1.2</li>
</ul>
</li>
<li data-expanded="true">Item 2
<ul>
<li data-expanded="true">Item 2.1
<ul>
<li>Item 1.1</li>
<li>Item 1.2</li>
</ul></li>
<li>Item 2.2</li>
</ul>
</li>
</ul>
<input id="dropdown"></input>
哪裏是你Ajax請求? – madalinivascu