如何获取knockoutjs可观察数组的下一个元素?
16lz
2021-01-22
I need to implement 2 buttons (next, previous) for array elements of an observable array. Is there any default function or any way to navigate between elements of the array?
我需要为可观察数组的数组元素实现2个按钮(next,previous)。是否有任何默认函数或任何方式在数组的元素之间导航?
Ex:
var mainArray = ko.observableArray([{id:1,name:'one'},{id:2,name:'two'}]);
When I click the next button, it should return the next object (like ko.utils.arrayFirst() returns the given object)
当我单击下一个按钮时,它应该返回下一个对象(如ko.utils.arrayFirst()返回给定对象)
Any help?
1 个解决方案
#1
2
Nope, there is no "default" way to do this.
不,没有“默认”方式来做到这一点。
RoyJ's comment is spot on about how to do it yourself. Let me turn it into a working example:
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>
更多相关文章
- 使用Jquery Ajax更改按钮的颜色(从外部PHP文件接收颜色)
- 显示json数组中的所有项目
- 图表。js数据数组使用PHP, MySQL。如何从JSON数组定义数据源?
- 将JavaScript对象转换为要插入关系数据库的数组
- javascript数组和对象是否有设置顺序?
- 从另一个数组中删除数组的内容。
- 从两个数组生成JSON
- 在单选按钮上选中/取消选中,加载/隐藏部分视图
- 如何将图像(PNG)转换为2D数组(二进制图像)?