我有一个3x3 HTML表格,每个元素都存储一个单独的<canvas>
元素
表格中有一个单元格包含text
而不是<canvas>
当单击包含图像的单元格并且右侧的单元格包含文本时,我正在尝试将该单元格的画布与存储在相邻单元格中的文本交换。
每次单击一个单元格时,使用以下代码,画布元素将消失并仅交换文本,使右侧的单元格不再包含文本或<canvas>
我尝试使用("#blankCell").html()
访问画布但它不起作用..有人知道如何访问此内容以交换值吗?
我为此创建了一个简化的jsFiddle:http://jsfiddle.net/bobbyrne01/dbMnM/1/
$(function () {
var $tbl = $('<table border="1">').attr('id', 'grid');
var $tbody = $('<tbody>').attr('id', 'tableBody');
var tileCount = 0;
var rowCount = $("#numOfPieces").val();
for (var i = 0; i < rowCount; i++) {
var trow = $("<tr>").attr('id', 'row' + i); // New row
for (var j = 0; j < rowCount; j++) {
$cell.append(canvasArray[tileCount]); // Each data cell contains separate canvas element
$cell.appendTo(trow);
tileCount++;
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove(); // removes previous table if it existed
$('body').append($tbl);
});
$('#grid tr:nth-child(2) td:last').prev().text("empty");
$('#grid tr:nth-child(2) td:last').prev().attr('id', 'blankCell');
收听点击次数..
$('body').on('click', '#grid td', function(e) {
var $this = $(this);
if ($(this).closest('td').next("#blankCell").length){
blank = $(this).closest('td').next("#blankCell");
if (blank.length) {
//alert('blank to the right');
$this.before(blank);
}
$(this).attr('id', 'blankCell');
$(this).closest('td').next("#blankCell").attr('id', 'piece');
}
感谢您的帮助!
现在只有文字,而不是使用画布元素进行交换
目标是,如果用户选择blankCell
旁边的单元格,我想将该单元格与blankCell
交换,如果用户选择不在blankCell
旁边的单元格,我希望不会发生任何事情。
现在只关注左右检测。
答案 0 :(得分:1)
简化并只交换整个表格单元格,而不是它们的内容或内容字符串和属性:
$('#grid').on('click', 'td', function(e) {
var $this = $(this),
blank = $this.next("#blankCell");
if (blank.length) {
//alert('blank to the right');
$this.before(blank);
}
});
好的,用于检查位置的一些更复杂的代码包括:
var empty = $("#empty").get(0);
$('#grid').on('click', 'td', function(e) {
if (!empty || this == empty) return; // abort, abort!
var currow = this.parentNode,
emptyrow = empty.parentNode;
var cx = this.cellIndex,
cy = currow.rowIndex,
ex = empty.cellIndex,
ey = emptyrow.rowIndex;
if (cx==ex && Math.abs(cy-ey)==1 || cy==ey && Math.abs(cx-ex)==1) {
// empty and this are next to each other in the grid
var afterempty = empty.nextSibling,
afterthis = this.nextSibling;
currow.insertBefore(empty, afterthis);
emptyrow.insertBefore(this, afterempty);
}
});