【发布时间】:2013-02-12 21:14:27
【问题描述】:
我正在尝试使用淘汰赛 js 创建一个具有 4 行和 4 列的表。下面是我的数组,它有 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();
【问题讨论】:
-
对于循环的“中断”.. 我建议你使用 div 和 position:relative;向左飘浮;它会做同样的事情,只是一开始有点棘手。
-
我支持@Yoeri 所说的,table、tr、td 结构是强制性的吗?您最终会得到一个更好的解决方案,使用 div 代替并使用 CSS(以及第 n 个子类型选择器)将它们定位在表结构中。
-
@ryadavilli 尝试使用 div 仍然无法正常工作...
标签: javascript arrays knockout.js foreach