簡體   English   中英

使用 JQuery 查找不在 header 中且僅在表的第一列中的單元格

[英]Find cells that are not in the header and are only in the first column of a table using JQuery

我曾經有過類似的東西,

$(elem).parents('li').find(...)

其中 elem 是列表中的一個項目,因此很容易獲得對列表中所有項目的引用。 然而,現在我添加了更多信息並決定使用一個表格,該列表適合如下表格。

[標題][標題][標題]

[列表 1][ 單元格 ][ 單元格 ]

[列表 2][ 單元格 ][ 單元格 ]

[列表 3][ 單元格 ][ 單元格 ]

我有點難以創建等效的 JQuery 僅在其中包含列表項的單元格上執行 a.find() 。 列表項始終位於最左側的表格單元格中,不包括 header。

這是 html 中的表格。

<table id="my-table">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
<tr>
<td>list item 1</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
<tr>
<td>list item 2</td>
<td>junk</td>
<td>junk</td>
<td>junk</td>
</tr>
</table>

如果 li 總是在每行的第一個單元格中,那么這應該有效:

$('td:first-child>li')

利用:

$(elem).closest('tr').find(...)

如果你使用theadtbody ,你可以更容易地在 body 中找到行。

將您的標記更改為如下所示:

<table>
    <thead>
       ... header rows ...
    </thead>
    <tbody>
       ... body rows ...
    </tbody>
</table>

然后,您可以簡單地將tbody包含在您的 jquery 選擇器中,以僅查找作為主體行的行。

#my-table tbody td:first-child類的東西。 first-child將在哪里為您提供第一列。

這將只為您提供每行中的第一列。

var rows = $('tr :nth-child(1)', '#my-table').not('th');

如果你現在想循環並做一些事情,只需使用:

rows.each(function()
{
   //Do something with the columnn
});

下面的解決方案將 output 匹配元素,每行中的第一個<td> ,到<div id="#results"

工作示例: http://jsfiddle.net/6faUf/

HTML:

<table border="5">
    <thead>
        <tr><th>1</th><th>2</th><th>3</th></tr>
    </thead>
    <tbody>
        <tr><td><ul><li>List1</li></ul></td><td>2</td><td>3</td></tr>
        <tr><td><ul><li>List2</li></ul></td><td>2</td><td>3</td></tr>
    </tbody>
</table>
<div id="results">The list values are: </div>

JavaScript(jQuery):

$('td:first-child').each(function(){
    var value = $(this).text();
    $("#results").append(value);
});

如果您需要其中包含列表項的單元格,則需要:has()選擇器,所以會有類似的東西:

  • $(elem).closest('table').find('td:has(li)...') — 如果您需要表中的所有li
  • $(elem).closest('tr').find('td:has(li)...') - 如果您需要原始中的所有li

暫無
暫無

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

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