简体   繁体   English

根据第一个单元格内容获取表单元格值

[英]Get table cell value based on the first cell content

I have a page with multiple dynamic tables , one of the table looks like the below structure 我有一个包含多个动态表的页面,其中一个表看起来像下面的结构

Col1 Col2 Col3
1    One  Two
2    b    15/12/2017
3    a    X
2    W    10/12/2014

HTML HTML

<table id="table1">
<tbody>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
<tr> <td>1</td>
     <td>b</td>
     <td>15/12/2017</td>
</tr>
<tr> <td>2</td>
     <td>b</td>
     <td>15/10/2017</td>
</tr>

<tr> <td>3</td>
     <td>b</td>
     <td>15/09/2017</td>
</tr>
</tbody>
</table>

I would like to know How can I get the cell in col3 with header name based on the value at col1 ? 我想知道如何基于col1的值获取具有标题名称的col3的单元格?

EX: EX:

I want to find the table by ID and check its first cell for each row, if it equal 2 then get the cell value of col 3 in the same row ! 我想按ID查找表并检查每行的第一个单元格,如果等于2,则在同一行中获取col 3的单元格值!

Any help would be fully appreciated 任何帮助将不胜感激

With jQuery it's quite easy; 使用jQuery,这非常容易。 if you've found the cell, get the row, and the third cell in that row; 如果找到了该单元格,则获取该行以及该行中的第三个单元格;

$('td') // Select all cells
.filter(function() { // Filter the cells
    return $(this).text() == '2';
})
.closest('tr') // get the table row
.find('td') // select all cells in that row
.eq(2) // select the third cell (0-based index)
.text(); // this will output '15/12/2017'

edit I'm in a good mood today, check this little demo; 编辑我今天心情很好,请查看这个小演示; https://jsfiddle.net/a32knb81/ . https://jsfiddle.net/a32knb81/ Just input your search key in the input field an you'll get the value of the third column in that same row. 只需在输入字段中输入搜索关键字,您将获得同一行中第三列的值。

You can try something with jquery like below snippet. 您可以使用jQuery尝试以下片段中的内容。

Update: you can get particular column by table header as well using $('th:contains("col3")').index() 更新:您还可以使用$('th:contains("col3")').index()通过表头获取特定列

 $(document).ready(function() { $('#myTable').find('tbody td:first-child').each(function() { if ($(this).text() == '2') { console.log($(this).closest('tr').find('td').eq($('th:contains("col3")').index()).text()); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myTable"> <thead> <th>col1</th> <th>col2</th> <th>col3</th> </thead> <tbody> <tr> <td>1</td> <td>one</td> <td>ONE</td> </tr> <tr> <td>2</td> <td>two</td> <td>TWO</td> </tr> <tr> <td>3</td> <td>three</td> <td>THREE</td> </tr> </tbody> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM