【发布时间】:2021-01-07 07:23:27
【问题描述】:
我正在尝试在更新数组属性时更新 UI,
我有颜色数组,我试图更新颜色数组中的红色,但它不会更新 UI
var ViewModel = function() {
this.self = this;
self.colors = ko.observableArray([
{ color: "red", test: "aaa" },
{ color: "blue", test: "bbb" },
{ color: "yellow", test: "ccc" }
]);
self.replaceIt = function() {
const result = self.colors().filter(c => c.color === "red");
result[0].color = "green";
for (var i = 0; i < self.colors().length; i++) {
self.colors.replace(self.colors()[0], result[0]);
}
};
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: colors">
<li>
<span data-bind="text:color"></span>
<span data-bind="text:test"></span>
</li>
</ul>
<br/>
<br/>
<button data-bind="click:replaceIt">Replace It</button>
结果 UI 始终显示
red aaa
blue bbb
yellow ccc
但是当我将属性红色更新为绿色时,我想更新 UI
green aaa
blue bbb
yellow ccc
【问题讨论】:
标签: knockout.js