簡體   English   中英

使用jQuery在表格列中的所有單元格上運行函數

[英]Run function on all cells in table column with jQuery

我有一個下面定義為$table的表元素。 我試圖在每個單元格上運行由特定表標題qc_statusTh定義的特定列的函數。 我已經找到該表標題的索引( qc_statusColumnIndex ),並且能夠獲取該列中的下一個表單元格qc_statusCell

但是,我無法遍歷表單元格並在該列中的每個表單元格上運行一個函數。

這是我到目前為止擁有的JavaScript代碼:

$(document).ready(function() {
  var $table = $("table.tables.list");

  if ($table.length > 0) {
    var qc_statusTh = $("th.headersub:contains('qc_status')");
    var qc_statusColumnIndex = $(qc_statusTh).index();
    var qc_statusCell = $($table).find("td").eq(qc_statusColumnIndex);

    // this does not work. this only replaces the first cell
    // in the row after qc_statusTh with "TESTING"

    $(qc_statusCell).each(function() {
      $(this).replaceWith("TESTING");
    });

  }

});

如何編輯此代碼以遍歷表中與qc_statusColumnIndex索引相等的每個單元格?

如果考慮一下,您真的想遍歷表的行而不是單元格(使用each )。 如果這樣做,則可以從每行中獲取第n個 td元素並應用轉換。

 $(document).ready(function() { var $table = $("table.tables.list"); if ($table.length > 0) { var qc_statusTh = $("th.headersub:contains('qc_status')"); var qc_statusColumnIndex = $(qc_statusTh).index(); var qc_rows = $($table).find('tr'); $(qc_rows).each(function() { $(this).find('td').eq(qc_statusColumnIndex).replaceWith("TESTING"); }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="tables list"> <thead> <th class="headersub">qc_example</th> <th class="headersub">qc_status</th> </thead> <tbody> <tr> <td>1</td> <td>Ok</td> </tr> <tr> <td>2</td> <td>Ok</td> </tr> <tr> <td>3</td> <td>Error</td> </tr> </tbody> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM