Reputation: 951
Here is my jfiddle: http://jsfiddle.net/D3zyt/8/
html:
<div class="board">
<table id="mastermind_table_one">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_two">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
You'll notice in the html that I have three tables. Is there a way when I click "next_round", the background colors change for the next table and not the current (hardcoded) table?
Upvotes: 1
Views: 100
Reputation: 1340
Note: this post contains a bad practice, I left it maybe someone could learn from it, read the comment
just use one table like:
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
and then add a button <button onclick="nextRound(this)
/>
with the function as:
function nextRound(that) {
that.i = that.i ? (that.i + 1) : 1;
$('table').removeClass("mastermind_table_" + that.i - 1);
$('table').addClass("mastermind_table_" + that.i);
}
Upvotes: 1
Reputation: 3892
This is a solution that implements event data in jquery.
And here is a fiddle: http://jsfiddle.net/D3zyt/10/
var randomColor = ["red", "blue", "green", "#9CBA7F", "yellow", "#BF5FFF"];
function setRandomColor() {
return randomColor[Math.floor(Math.random() * randomColor.length)];
}
$('.next_round').on("click", {i: 0}, function(e) {
var selectorFragment = ["one","two","three"]
$('#mastermind_table_'+selectorFragment[e.data.i]).each(function() {
$(this).find('td').each(function() {
$(this).css("background-color", setRandomColor);
})
})
e.data.i += 1
if (e.data.i === 3) e.data.i = 0
})
However, restructuring your html would probably make for an easier solution later down the road ;)
Upvotes: 1
Reputation: 64526
This does it by storing the current table in a variable and using .next()
to find the next table:
var current;
$('.next_round').click(function() {
if(typeof current == 'undefined' || current.next('table').length == 0){
current = $('.board table').first();
} else {
current = current.next('table');
}
$(current).find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
});
Upvotes: 2
Reputation: 4521
Something like this helps?
var tables = $('.board table');
var currentTable = 0;
$('.next_round').click(function() {
var table = tables[currentTable];
table.find('td').each(function() {
$(this).css("background-color", setRandomColor);
});
currentTable++;
if(currentTable > tables.length){
currentTable = 0;
}
}
Upvotes: 1