[英]How can I add an icon into a binding without it deleting it?
我正在嘗試創建一個帶有下拉菜單的菜單欄,當單擊該菜單欄時,它將顯示下拉菜單,還將圖標從右箭頭更改為向下箭頭。 但是,Knockout JS會繼續刪除綁定內的span標簽。 我該如何解決?
這是我的html:
<!-- Recursively traverse the nested structure -->
<ul data-bind="template: {name: 'document_index_template', foreach: children}"><l><a href="#">Document Index</a></l></ul>
<script type="text/html" id="document_index_template">
<li class="collapsible-child" >
<a data-bind="text: label, click: function(){isExpanded(!isExpanded())}" href="#"><span class="glyphicon glyphicon-triangle-right" ></span></a>
<ul class="collapsible-child" data-bind='template: { name: "document_index_template", foreach: visibleChildren}'></ul>
</li>
</script>
這是我的ViewModel:
var document_type = 'loan';
var key = 'comparison';
define(['jquery', 'knockout'], function($, ko){
var structureRequest = getStructure();
structureRequest.then(function(data){
window.treeNode = new TreeNode(data);
ko.applyBindings(window.treeNode);
});
function TreeNode(data){
var self = this;
self.key = ko.observable(data.key);
self.label = ko.observable(data.label);
self.children = ko.observableArray([]);
$.each(data.children, function(index, child){
self.children.push(new TreeNode(child));
});
self.isExpanded = ko.observable(false);
self.visibleChildren = ko.computed(function(){
if(self.isExpanded()){
return self.children();
}else{
return [];
}
});
}
function getStructure() {
var url = "../structure/api/0?document_type=" + document_type + "&key=" + key;
return $.ajax({
url: url,
type: "GET",
dataType: "json"
});
}
});
text
數據綁定清除節點並注入文本節點。 您必須將文本綁定向下移動一級:
<a data-bind="click: function(){ isExpanded(!isExpanded()) }" href="#">
<span data-bind="text: label"></span>
<span class="glyphicon glyphicon-triangle-right"></span>
</a>
供參考:這是來自淘汰賽的評論:
我們需要有一個孩子:一個文本節點。 如果沒有子節點(不止一個),或者如果它不是文本節點,我們將清除所有內容並創建一個文本節點。
https://github.com/knockout/knockout/blob/master/src/utils.js#L433
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.