我使用下面的代码,这段代码工作正常。
但是我想在标签检查,标签绑定删除按钮时以及点击删除时,需要取消选中。
这段代码怎么可能?
<div id="current-selected" style="" data-bind="text: selectedChoicesDelimited">
<a href="" id="clearAll" >Clear All</a>
</div>
<div data-role="content" class="filter-options-content" role="tabpanel" aria-hidden="false">
<ol class="items mcs-items" data-bind="foreach: choices">
<li>
<label>
<input id="5" class="multifilter" value="attribute?activity?5" type="checkbox" data-bind="attr: { value: $data }, checked: $parent.selectedChoices" ><span data-bind="text: $data"><input type="button" value="Remove Task" data-bind="click: $parent.removeChoices"></span>
</label>
</li>
</ol>
</div>
<script type="text/javascript">
var viewModel = {};
viewModel.choices = ["Outdoor", "Recreation", "Gym"];
viewModel.selectedChoices = ko.observableArray([]);
viewModel.selectedChoicesDelimited = ko.dependentObservable(function () {
return viewModel.selectedChoices().join(",");
});
ko.applyBindings(viewModel);
</script>
在图像下方,输出此代码。
下图,我想要。单击[x]时,取消选中值。
答案 0 :(得分:1)
首先让我解释一下,无论何时使用text
绑定它的功能,它实际上都会显示您传递给关联DOM元素的参数的文本值。事实上,knockout使用您的参数将元素的内容设置为text node
。任何嵌套元素内容都将被覆盖。我在您的代码中看到您在text-binding
内有一个子DOM元素。
<div id="current-selected" style="" data-bind="text: selectedChoicesDelimited">
<!-- this content will be overwritten by value of a your parameter -->
<a href="" id="clearAll" >Clear All</a>
</div>
或者再来一次
<span data-bind="text: $data">
<!-- this content will be overwritten by value of a your parameter -->
<input type="button" value="Remove Task" data-bind="click: $parent.removeChoices">
</span>
我将采取哪些措施来实现您所寻找的目标。
工作示例:https://jsfiddle.net/kyr6w2x3/80/
HTML:
<ul>
<!-- ko foreach: selectedChoices -->
<li>
<div>
<span data-bind="ifnot:$index() === 0">,</span>
<span data-bind="text:$data"></span>
<span data-bind="click:$parent.removeSelectedItem" class="remove">[x] </span>
</div>
</li>
<!-- /ko -->
<li>
<a href="" id="clearAll" data-bind="click:removeAllSelectedItem ,visible:selectedChoices().length > 1" >Clear All</a>
</li>
</ul>
<div data-role="content" class="filter-options-content" role="tabpanel" aria-hidden="false">
<ol class="items mcs-items" data-bind="foreach: choices">
<li>
<label>
<input id="5" class="multifilter" value="attribute?activity?5" type="checkbox" data-bind="attr: { value: $data }, checked: $parent.selectedChoices" ><span data-bind="text: $data"></span>
</label>
</li>
</ol>
</div>
JS:
var viewModel = {};
viewModel.choices = ["Outdoor", "Recreation", "Gym"];
viewModel.selectedChoices = ko.observableArray([]);
viewModel.removeSelectedItem = function(data){
ko.utils.arrayForEach(viewModel.selectedChoices(), function (item) {
if (item === data)return viewModel.selectedChoices.remove(item);
});
}
viewModel.removeAllSelectedItem = function(data){
viewModel.selectedChoices([]);
}
ko.applyBindings(viewModel);