表循环不工作jquery

时间:2018-01-18 07:35:43

标签: jquery html

$(".btnclass").click( function() {
    var row = $("table").find("tr");
    $.each( row, function() {
        $col = $(this).find("td");
        $.each( $col, function() {
            var one = "1";
            var zero = "0";
            var $k = $(this).css("background-color");
            if( $k === 'rgb(15, 210, 15)' ) {
                s.push( one );
            } else {
                s.push( zero );
            }
        });
    });
});

我是jquery的新手,我正试图遍历htm表 它不工作.. 我试图检查td是否有颜色并根据该值推送值... 我搜索了它找不到它.. 如果有人知道锄头做.. 给我链接...... 感谢

1 个答案:

答案 0 :(得分:0)

您可以简化代码,如下所示: -

$(document).ready(function(){ //when document is ready
  var s= []; //a empty array declration
  $(".btnclass").click(function(){ // on click of button
    $("table").find("tr td").each(function(){ // directly traverse each td of table
      var k= $(this).css("background-color"); // get td backgrond-color
      if(k==='rgb(15, 210, 15)'){ // compare to color
        s.push(1); // matched then push 1 to array
      }else{
        s.push(0); // otherwise push 0 to array
      }
    });
    console.log(s); // check array
   });
});

示例硬编码表示例。



$(document).ready(function(){
  var s= [];
  $(".btnclass").click(function(){
    $("table").find("tr td").each(function(){
      var k= $(this).css("background-color");
      if(k==='rgb(15, 210, 15)'){
        s.push(1);
      }else{
        s.push(0);
      }
    });
    console.log(s);
   });
});

td:nth-child(even) {background-color: rgb(15, 210, 15)}
td:nth-child(odd) {background: #FFF}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

<button class="btnclass">Click Me</button>
&#13;
&#13;
&#13;

相关问题