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部分没有。
谁能指点我一下吗?
谢谢。
发布于 2014-11-27 12:24:53
对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
}发布于 2014-11-27 12:24:37
您正在尝试调用在单击处理程序中未定义的函数。它应该是:
$('td').click(function() {
move(parseInt($(this).attr('id')), this);
});编辑:添加了parseInt,这样它将传递一个数字,而不是它的字符串表示形式。
https://stackoverflow.com/questions/27170396
复制相似问题