使用淘汰赛 js 我试图创建一个有 4rows 和 4coulmns 的表。下面是我的数组,它有 16 个元素,需要放入表中。
/*----------------------------------------------------------------------*/
/* View Model */
/*----------------------------------------------------------------------*/
function ViewModel() {
var self = this;
self.items = ko.observableArray(["1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg"
]);
self.itemRows = ko.computed(function () { //computes the rows dynamically based on items
var rows = [];
var count = 0;
var items = self.items(); //get the item array
var current = [];
for(var i in items)
{
var item = items[i];
current.push(item);
count++;
if (count == 4)
{
count = 0;
rows.push(current);
current = []; //next array
}
}
if (current.length > 0)
{
rows.push(current);
}
return rows;
});
self.bindSort = function() {
var startIndex = -1;
var sortableSetup = {
start: function (event, ui)
{
startIndex = ui.item.index();
},
stop: function (event, ui)
{
var newIndex = ui.item.index();
if (startIndex > -1)
{
self.from = ko.observable(startIndex);
self.to = ko.observable(newIndex);
var iTo = parseInt(self.to());
var iFrom = parseInt(self.from());
var from = self.items()[iFrom];
var to = self.items()[iTo];
self.items()[iTo] = from;
self.items()[iFrom] = to;
//alert('before');
// alert(from);
// alert(to);
var fromA = self.items()[iFrom];
var toA = self.items()[iTo];
//alert('after');
//alert(fromA);
// alert(toA);
self.items.remove(from);
self.items.splice(newIndex, 0, toA);
self.items.remove(to);
self.items.splice(startIndex, 0, fromA);
//ui.item.remove();
self.items.valueHasMutated();
}
}
};
$(".fruitList").sortable( sortableSetup );
};
}
/*----------------------------------------------------------------------*/
/* KO HTML Binding */
/*----------------------------------------------------------------------*/
$(document).ready(function() {
// create the view model
var model = new ViewModel();
// call the bind method for jquery UI setup
model.bindSort();
// binds ko attributes with the html
ko.applyBindings(model);
});
并尝试在 html 中执行此操作,
<table data-bind="foreach: itemRows">
<tr class="fruitList" data-bind="foreach: $data">
<td><img data-bind="attr: { src: $data }" /></td>
</tr>
</table>
我无法获得数组的长度,以及如何在第一行创建 4 个 tds 然后创建第二行时打破循环。有什么建议吗???
更新:
当我使用可排序时,下面的代码似乎不起作用,
start: function (event, ui)
{
startIndex = ui.item.index();
},
stop: function (event, ui)
{
var newIndex = ui.item.index();