2

我想获取我的表格单元格的 .html() 抛出 jQuery 只知道它的 data-col 和 data-row 属性。这是表格:

<table>
    <tr>
        <td></td>
        <th data-col="A">Mon</th><th data-col="B">Tue</th>
        <th data-col="C">Wen</th>
    </tr>
    <tr>
        <th data-row="1">Mon</th>
        <td>Something</td>
        <td>Something</td>
        <td>Somthing</td>
    </tr>
    <tr>
        <th data-row="2">Mon</th>
        <td>Something</td>
        <td>Something</td>
        <td>Somthing</td>
    </tr>
    <tr>
        <th data-row="3">Mon</th>
        <td>Something</td>
        <td>Something</td>
        <td>Somthing</td>
    </tr>
</table>

我不知道如何构建这个 jQuery 选择器,例如:$('table>tbody>tr[data-row=2] td')但我不知道

谢谢你的帮助

4

3 回答 3

2

jsBin 演示

function getTD(col, row){

   var rowIdx = $('[data-row='+row+']').parent('tr').index() ;
   var colIdx = $('[data-col='+col+']').index() -1;

   return $('tr:eq('+rowIdx+') td:eq('+colIdx+')').html() ; 
}

alert(   getTD('A', '2')    );

或者你也可以这样做:

演示

function getTD(c,r) {

  var col = {A:1, B:2, C:3}; // add more if needed

  var colLen = $.map(col, function(n, i) { return i; }).length;
  var cc =  colLen*(r-1) + col[c]; 
  return $('table').find('td').eq(cc).html();

}

alert(   getTD('B', 3)   );

如果您也使用 Numbers 来检索 COL,那么第二种解决方案的巧妙之处可能会更有趣:

function getTD(col,row) {     
  var ind =  (row-1)*3 + col; // 3 is the max N of Cols
  // 'ind' holds the exact index number of our desired TD from our .find() collection
  return $('table').find('td').eq( ind ).html();     
}

// getTD( COL, ROW )
alert(   getTD(2, 3)   );
于 2012-12-24T13:51:54.280 回答
1

解决方案的快速草图:

// Param table: the <table> DOM element,
// Param col: the string identifying the column,
// Param row: the string identifying the row
function(table, col, row) {
  col_number = $(table).find("tr").first().find("th[data-col=" + col + "]").index(); 
  row_number = $(table).find("th[data-row=" + row + "]").parent().index(); 
  return $(table).find("tr").eq(row_number).find("td").eq(col_number).val();
}

未经测试,并且可能以各种方式出现错误。尽管如此,在 jQuery 文档的帮助下,总体思路应该是清晰易懂的。

于 2012-12-24T13:39:46.233 回答
0

如果您用索引标记 cols,则该解决方案可能比 Confusion 的答案更小更快。

/**
 param table - DOM element of table
 param row - row index
 param col - col index
*/
function getData(table, row, col) {
    return $(table).find('tr:nth-child('+(row+1)+')').find('td:nth-child('+(col+1)+')').html();
}

此功能将满足您的需求。

JS Bin 演示

于 2012-12-24T13:50:31.660 回答