繁体   English   中英

使用JavaScript遍历表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM