Knockout.JS如何绑定dom元素绑定 [英] Knockout.JS How to bind dom element bind
本文介绍了Knockout.JS如何绑定dom元素绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用敲除绑定绘制在JS中生成的类别树, 但我无法与DOM元素绑定.
I want to draw my category tree that generated in JS using knockout binding, but I can not binding with DOM Element.
<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());
如果运行上面的代码,它将打印出来,
If run above code, it print,
[对象HTMLUListElement]
我应该如何绑定元素数据?
How should I do to make bind with Element data?
推荐答案
或者您可以像这样简单地更新可观察对象:
Or you could simply update the observable like this:
var html = $(appendSubCategories(categoryList)).html();
self.categoryTree(html);
这篇关于Knockout.JS如何绑定dom元素绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文