我想绘制使用淘汰绑定在 JS 中生成的类别树,但我无法与 DOM 元素绑定。
<div id="category_list" data-bind="html:categoryTree">
List Area
</div>
//JS
function appendSubCategories(categories) {
var container = document.createElement("ul");
$.each(categories, function (i, category) {
var currentNode = document.createElement("li");
var span = document.createElement("span");
span.setAttribute("style", "margin-left: 2px");
span.className = "folder";
span.appendChild(document.createTextNode(category.Name));
currentNode.appendChild(span);
if (category.Subfolders.length > 0) {
currentNode.appendChild(appendSubCategories(category.Subfolders));
}
container.appendChild(currentNode);
});
return container;
}
function CategoryViewModel() {
var self = this;
self.categoryTree =ko.observable();
$(function () {
$.getJSON("/Admin/Category/getCategoryList", function (categoryList) {
self.categoryTree(appendSubCategories(categoryList));
//self.categoryTree("<p>This is working</p>);
//$("#category_list").html(categoryTree);
$(".folder").click(function () {
console.log(this);
});
});
});
}// End CategoryViewModel
ko.applyBindings(new CategoryViewModel());
如果运行上面的代码,它会打印,
[对象 HTMLUListElement]
我应该怎么做才能与元素数据绑定?