使用Javascript迭代表

时间:2014-04-24 19:38:03

标签: javascript jquery html iteration

这是我的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”时,下一个表的背景颜色会改变而不是当前(硬编码)表?

4 个答案:

答案 0 :(得分:2)

这是通过将当前表存储在变量中并使用.next()来查找下一个表来实现的:

Fiddle

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);
   });

});

答案 1 :(得分:1)

这样的事情有帮助吗?

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;
    }
}

答案 2 :(得分:1)

注意:这篇文章包含一个不好的做法,我离开了它也许有人可以从中吸取教训,阅读评论

只需使用一个表格,如:

<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>

然后添加按钮<button onclick="nextRound(this) /&gt;

功能为:

function nextRound(that) {
that.i = that.i ? (that.i + 1) : 1; 
$('table').removeClass("mastermind_table_" + that.i - 1);
$('table').addClass("mastermind_table_" + that.i);
}

答案 3 :(得分:1)

这是一个在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可能会在以后的路上提供更简单的解决方案;)

相关问题