gpt4 book ai didi

javascript - 在 td 旁边的 HTML 表格中查找 td 文本

转载 作者:行者123 更新时间:2023-11-29 16:50:14 25 4
gpt4 key购买 nike

我试图在带有文本“我的元数据”的 td 旁边找到表 td 中的文本。我正在尝试遍历表 tds 等以找到它。有什么非常简单的方法可以在 td 中搜索与 td 相邻且具有某些值的文本吗?

Here is my fiddle

<table id="searchTable">
<tr>
<td>
My Metadata
</td>
<td>
I want to alert this td text which is next to td which has text My Metadata
</td>
</tr>
</table>

最佳答案

您可以使用 :contains() next()

  • 使用 :contains() 选择器,您可以获得包含特定文本的元素。
  • 然后使用 next() 得到它旁边的 sibling 。

var text = $('#searchTable td:contains(My Metadata)') // get td which contains the text
.next() // get sibling next to it
.text(); // get text content in it

console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="searchTable">
<tr>
<td>
My Metadata
</td>
<td>
I want to alert this td text which is next to td which has text My Metadata
</td>
</tr>
</table>


如果要选择完全匹配的元素,请使用 filter()

var text = $('#searchTable td').filter(function() {
return $.trim($(this).text()) == 'My Metadata'; // check trimmed content and filter based on that
})
.next() // get sibling next to it
.text(); // get text content in it

console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="searchTable">
<tr>
<td>
My Metadata
</td>
<td>
I want to alert this td text which is next to td which has text My Metadata
</td>
</tr>
</table>


更新:如果 html 内容在变量中,那么您可以执行以下操作。

var content = `<table id="searchTable">
<tr>
<td>
My Metadata
</td>
<td>
I want to alert this td text which is next to td which has text My Metadata
</td>
</tr>
</table>`;

var text = $(content).find('td:contains(My Metadata)') // get td which contains the text
.next() // get sibling next to it
.text(); // get text content in it

console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - 在 td 旁边的 HTML 表格中查找 td 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com