[英]Iterating through tables with Javascript
這是我的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>
您會在html中注意到我有三個表。 當我單擊“ next_round”時,有什么方法可以改變下一張表的背景顏色,而不是當前(硬編碼)表的背景色嗎?
通過將當前表存儲在變量中並使用.next()
查找下一個表來完成此操作:
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);
});
});
這樣的事情有幫助嗎?
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;
}
}
注意:這篇文章包含一個不好的做法,我離開了它,也許有人可以從中學到,閱讀評論
只需使用一個表,例如:
<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>
然后添加一個按鈕<button onclick="nextRound(this)
/>
具有以下功能:
function nextRound(that) {
that.i = that.i ? (that.i + 1) : 1;
$('table').removeClass("mastermind_table_" + that.i - 1);
$('table').addClass("mastermind_table_" + that.i);
}
這是在jquery中實現事件數據的解決方案。
這是一個小提琴: 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
})
但是,重組HTML可能會為以后的解決方案提供一個更簡單的解決方案;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.