gpt4 book ai didi

javascript - 如何将图标添加到绑定(bind)中而不删除它?

转载 作者:行者123 更新时间:2023-12-03 06:27:17 26 4
gpt4 key购买 nike

我正在尝试创建一个带有下拉菜单的菜单栏,单击时,它将显示下拉菜单,并将图标从右箭头更改为向下箭头。但是,Knockout JS 不断删除绑定(bind)内的 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 数据绑定(bind)会清理节点并注入(inject)文本节点。您必须将文本绑定(bind)向下移动一级:

<a data-bind="click: function(){ isExpanded(!isExpanded()) }" href="#">   
<span data-bind="text: label"></span>
<span class="glyphicon glyphicon-triangle-right"></span>
</a>

供引用:这是来自 knockout 来源的评论:

We need there to be exactly one child: a text node. If there are no children, more than one, or if it's not a text node, we'll clear everything and create a single text node.

https://github.com/knockout/knockout/blob/master/src/utils.js#L433

关于javascript - 如何将图标添加到绑定(bind)中而不删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38597219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com