我正在嘗試製作燈光遊戲。當我點擊它們時,我可以打開和關閉燈光,但是我很難想出邏輯來使相鄰的燈光也一樣。例如,如果我點擊桌子的邊緣,我應該看到與點擊的燈光相鄰的三個燈光變亮。我在想,也許它與我的點擊方法中的「this」邊界有關,也許「this」只是引用我點擊的那個,而不是相鄰的那個。我需要知道,也許如何讓它參考相鄰的?在JQuery中觸發事件時更改表中的相鄰單元格
<html>
<head>
<title>Lights Out!</title>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type= "text/javascript">
var gameBoard = new Array(getTdCount())
function lightStatus(position)
{
//if light is on
if(gameBoard[position] ==true)
{
//set the original status back to false
gameBoard[position] = false;
return false
}
//turn on light
gameBoard[position]=true;
return gameBoard[position]
}
function getTdCount()
{
return $("td").length;
}
function getTrCount()
{
return $("tr").length;
}
function switchLights(obj, num)
{
if(lightStatus(num))
{
$("img", obj).attr('src', 'on.png')
}
else
{
$("img", obj).attr('src', 'off.png')
}
}
$(document).ready(function()
{
$("#board tr td").hover(function()
{
$(this).css('border-color', '00FFCC');
},
function()
{
$(this).css('border-color', 'black')
})
var $offProtoType = $('#offprototype').css('display', 'block').removeAttr('id')
$('td').append($offProtoType)
$tds = $('#board tr td');
$tds.click(function()
{
var num = $tds.index(this) + 1;
switchLights(this, num)
})
});
</script>
<style type="text/css">
td
{
border-style:solid;
border-color:black;
background-color:black;
float:left;
}
body
{
background-color: grey;
color: green;
}
</style>
</head>
<body>
<img style = "display:none" id="offprototype" src ="off.png">
<img style = "display:none" id="onprototype" src ="on.png">
<h1 align="center">Lights Out<h1>
<table id="board" border="3" bgcolor="black" align="center">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<input type="button" value="Shuffle" onclick="change()"/>
</body>
</html>