我需要为可观察数组的数组元素实现 2 个按钮(下一个、上一个)。是否有任何默认函数或任何方式在数组元素之间导航?
例如:
var mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);
当我点击下一步按钮时,它应该返回下一个对象(比如 ko.utils.arrayFirst() 返回给定的对象)
有什么帮助吗?
最佳答案
不,没有“默认”方式来做到这一点。
RoyJ 的评论是关于如何自己做的。让我把它变成一个工作示例:
var ViewModel = function() {
var self = this;
self.mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);
var _currentItemIndex = ko.observable(0);
function navigate(nrOfSpots) {
if (_currentItemIndex() + nrOfSpots >= self.mainArray().length) { return; }
if (_currentItemIndex() + nrOfSpots < 0) { return; }
_currentItemIndex(_currentItemIndex() + nrOfSpots);
}
self.next = function() { navigate(1); };
self.prev = function() { navigate(-1); };
self.currentItem = ko.computed(function() {
return self.mainArray()[_currentItemIndex()];
});
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Current Item:
<i data-bind="text: currentItem().name"></i>
<br />
<button data-bind="click: prev">Previous</button>
<button data-bind="click: next">Next</button>
它利用:
- 一个带有指示当前索引的可观察变量的私有(private)变量;
prev
和next
两个函数来更改该索引(到目前为止有效/可能);- A 计算返回该索引处的当前项。
View (html) 仅用于演示目的。
关于javascript - 如何获取 knockoutjs 可观察数组的下一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30867450/