我发现的所有 knockout 示例似乎都使用类似以下内容将新项目添加到 ObservableArray 的末尾:
viewModel.SomeItems.push(someNewItem);
这当然会将项目放在数组的末尾。
如何在 ObservableArray 的某个位置添加一个项目?
例如。像这样的东西:
viewModel.SomeItems.push(someNewItem, indexToInsertItAt);
最佳答案
你应该可以使用原生 JavaScript splice
方法 -
viewModel.SomeItems.splice(2,0,someNewItem);
文档在这里 - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
此处示例(非特定于 Knockout)- How to insert an item into an array at a specific index?
来自 Knockout 文档 -
For functions that modify the contents of the array, such as push and splice, KO’s methods automatically trigger the dependency tracking mechanism so that all registered listeners are notified of the change, and your UI is automatically updated.
关于javascript - 如何使用 Knockout.js 在特定位置向 ObservableArray 添加/插入项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7317907/