When I click on a TD I need to make the background color red, and the 4 td's connected to it need to get the background color grey. When I click on a other TD the previous td's need to go white again and the new td has to color red and the others connected to it grey.
The right, left, above, and bottom of the RED TD need to get the color grey. Also the previous clicked TD need to stay but when i click on another td the first one needs to go away.
This is what I already have:
HTML
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Jquery
$('document').ready(function (){
$('td').click(function (){
var $this = $(this);
var col = $this.index() + 1;
var row = $this.closest('tr').index() + 1;
$(this).css('background-color', 'red')
$('p').text('Je zit nu in kolom ' + col + ' en in rij ' + row);
})
});
答案 0 :(得分:1)
So something like this
$('document').ready(function() {
var $td = $('td').click(function() {
if ($(this).hasClass('grey')) {
alert("can't click");
} else {
var $this = $(this);
var col = $this.index() + 1;
var row = $this.closest('tr').index() + 1;
$td.removeClass('red grey'); // set all td's color white
$('tr:nth-child(' + (row - 1) + '),tr:nth-child(' + (row + 1) + ')')
.find('td:nth-child(' + col + ')') // get the clicked column td's
.addClass('grey');
$(this).addClass('red') // set clicked td's color red
.parent()
.find('td:nth-child(' + (col - 1) + '),td:nth-child(' + (col + 1) + ')')
.addClass('grey'); // set color to grey
$('p').text('Je zit nu in kolom ' + col + ' en in rij ' + row);
}
})
});
td {
width: 20px;
height: 20px;
}
.grey {
background-color: grey
}
.red {
background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border=1>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<p></p>
答案 1 :(得分:1)
$('document').ready(function ()
{
$('td').click(function ()
{
var row = $(this).closest('tr');
$(row).find('td').css('background-color', 'grey');
$(this).css('background-color', 'red');
})
});