JQUERY - 在具有特定类的表格单元格中获取数据

时间:2014-02-27 01:09:42

标签: jquery javascript

我有一张如下表:

<table id="Grid">
 <thead>
  <tr>
     <th>Month</th>
     <th>Savings</th>
  </tr>
 </thead>
 <tbody>
  <tr>
     <td>January</td>
     <td class="k-dirty-cell">$100</td>
  </tr>
  <tr>
     <td>February</td>
     <td class="k-dirty-cell">$80</td>
  </tr>
  <tr>
     <td>March</td>
     <td>$98</td>
  </tr>
 </tbody>
</table>

我想通过class =“k-dirty-cell”迭代(或解析)单元格并获取其值并验证它是否为null。

该类总是在第二列,所以我只想迭代第二列的行 - 即,当cellIndex = 2时。

到目前为止我已经尝试过这个但是我有点卡住了:

$("#Grid tbody").find('td').each(
    function () {
        debugger;

        // run for specific columns - where validation is needed
      //  var isDirty = cellToValidate.hasClass('k-dirty-cell');

       var isDirty = $(this).hasClass('k-dirty-cell');
        if (isDirty == true) {

            var cellContent = $(this).context.innerText;
            var cellIndex = $(this).context.cellIndex;

       //     alert(cellContent + cellIndex);

        }
    });

如果可以,请你帮忙。

非常感谢。

3 个答案:

答案 0 :(得分:2)

如果您的主要目标是I would like to iterate (or parse) through cells with class="k-dirty-cell" and get its value and validate whether it is null or not.,则以下内容就足够了:

$(function() {
  $('td.k-dirty-cell').each(function() {
    var cellValue = $(this).text();
    //do something with cellValue 
    if(cellValue) {
      //not null  
    } else {
      //null
    }
  });
});

编辑: 由于可能存在类位于第一列的情况(每个评论讨论),以下内容将仅选择具有k-dirty-cell类的第二列项:

$(function() {
    $('tr td:nth-child(2).k-dirty-cell').each(function() {
    var cellValue = $(this).text();
      alert(cellValue)
    //do something with cellValue 
    if(cellValue) {
      //not null  
    } else {
      //null
    }
  });
});

示例小提琴:http://jsfiddle.net/tztLD/

答案 1 :(得分:2)

$(".k-dirty-cell").each(function() {
    // your code
});

应该做的伎俩。

答案 2 :(得分:2)

您只需要获取其类td的所有k-dirty-cell标记,这样就足够了:

$("#Grid td.k-dirty-cell").each(function() {
    if($(this).text().length > 0) {
       alert("value: " + $(this).text());
     }
}