Py学习  »  Jquery

如何使用jquery选择表中哪一行包含特定值?[关闭]

TIROGEN • 5 年前 • 1588 次点击  

我有如下html表

<table>
  <tr>
    <td>ABC</td>
    <td>Smith</td>
  </tr>
  <tr>
    <td>DEF</td>
    <td>John</td>
  </tr>
  <tr>
    <td>GHI</td>
    <td>Harry</td>
  </tr>
</table>

我想用javascript获取第一列包含“E”的行的html代码(没有jquery)

结果如下。

<tr>
  <td>DEF</td>
  <td>John</td>
</tr>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51691
文章 [ 2 ]  |  最新文章 5 年前
Gabriele Petrioli
Reply   •   1 楼
Gabriele Petrioli    5 年前

通过检查你想要的手机 .text() 然后使用 .closest 到表行,最后得到 outerHTML DOM节点的。

const rowWithE = $('td:first-child').filter(function() {
  return $(this).text().includes('E')
}).closest('tr').get(0).outerHTML;


console.log(rowWithE);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
  <tr>
    <td>ABC</td>
    <td>Smith</td>
  </tr>
  <tr>
    <td>DEF</td>
    <td>John</td>
  </tr>
  <tr>
    <td>GHI</td>
    <td>Harry</td>
  </tr>
</table>

当然,如果没有jquery,您也可以这么做

const rowWithE = [...document.querySelectorAll('td:first-child')].filter(function(node) {
  return node.textContent.includes('E');
})[0].parentNode.outerHTML;


console.log(rowWithE);
<table>
  <tr>
    <td>ABC</td>
    <td>Smith</td>
  </tr>
  <tr>
    <td>DEF</td>
    <td>John</td>
  </tr>
  <tr>
    <td>GHI</td>
    <td>Harry</td>
  </tr>
</table>
Ankur Mishra
Reply   •   2 楼
Ankur Mishra    5 年前
var html = $("table tr td:contains(E)").closest('tr').get(0).outerHTML;
console.log(html);