Javascript
脚本:
function move(cellID, cell) {
if (cellID==emptyCell) return;
rest = cellID % 5;
topPos = (cellID>5) ? cellID-5 : -1;
bottomPos = (cellID<21) ? cellID+5 : -1;
leftPos = (rest!=1) ? cellID-1 : -1;
rightPos = (rest>0) ? cellID+1 : -1;
if (emptyCell!=topPos && emptyCell!=bottomPos && emptyCell!=leftPos && emptyCell!=rightPos)
return;
cell1 = document.getElementById(emptyCell);
img1 = cell1.firstChild;
img = cell.firstChild;
cell.removeChild(cell.firstChild);
cell1.removeChild(cell1.firstChild);
cell.appendChild(img1);
cell1.appendChild(img);
emptyCell = cellID;
}
HTML:
<table>
<tr>
<td id="1" onClick="move(1,this);"></td>
<td id="2" onClick="move(2,this);"></td>
<td id="3" onClick="move(3,this);"></td>
<td id="4" onClick="move(4,this);"></td>
<td id="5" onClick="move(5,this);"></td>
</tr>
<tr>
<td id="6" onClick="move(6,this);"></td>
....
</table>
Javascript 和 JQuery
脚本:
$('td').click(function() {
move(this.attr('id'), this);
});
function move(cellID, cell) {
if (cellID==emptyCell) return;
rest = cellID % 4;
topPos = (cellID>5) ? cellID-4 : -1;
bottomPos = (cellID<13) ? cellID+4 : -1;
leftPos = (rest!=1) ? cellID-1 : -1;
rightPos = (rest>0) ? cellID+1 : -1;
if (emptyCell!=topPos && emptyCell!=bottomPos && emptyCell!=leftPos && emptyCell!=rightPos)
return;
cell1 = document.getElementById(emptyCell);
img1 = cell1.firstChild;
img = cell.firstChild;
cell.removeChild(cell.firstChild);
cell1.removeChild(cell1.firstChild);
cell.appendChild(img1);
cell1.appendChild(img);
emptyCell = cellID;
}
HTML:
<table>
<tr>
<td id="1" ></td>
<td id="2" ></td>
<td id="3" ></td>
<td id="4" ></td>
</tr>
<tr>
<td id="5" ></td>
...
</table>
好的,所以我正在慢慢尝试使用 jquery 库将益智游戏从 javascript 转换为 javascript。我在 javascript 和 jquery 中都成功地加载了拼图的部分,其中拼图的各个部分加载在屏幕上,但现在我无法让 move
函数工作。 move
函数应该是在单击事件时移动棋子的函数。代码的纯 javascript 部分完全有效。但是 jquery 部分没有。
谁能教教我?
谢谢。
最佳答案
好吧,使用 JQuery,您有上百万种方法可以做到这一点。其中之一如下:
function moveCells(cell1id, cell2id) {
var cell1=$("#"+cell1id), // your first cell
cell2=$("#"+cell2id), // your second cell
cell1contents=cell1.html(), // whatever's inside the 1st cell
cell2contents=cell2.html(); // whatever's inside the 2nd cell
cell2.html(cell1contents); // put in 2nd cell whatever was inside the 1st
cell1.html(cell2contents); // put in 1st cell whatever was inside the 2nd
}
关于javascript - 使用 jquery 将纯 javascript 编写的拼图转换为 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170396/