javascript - 通过邻居获取 TD 内的文本 THE 内部文本

标签 javascript jquery find

我需要使用 jQuery 通过相邻 TH 的文本值来获取没有 ID 或类的特定 TD 的值

示例:

<table>
    <tbody>
        <tr>
            <th>Established</th>
            <td>1976</td>
        </tr>
        <tr>
            <th>Location</th>
            <td>Baltimore, Maryland</td>
        </tr>
    </tbody>
</table>

我想通过搜索“Established”来获取 1976 年(使用 jQuery)
交易/订单的位置并不总是相同。

可能吗?

最佳答案

var year = $("th:contains('Established')").next().text();

console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th>Established</th>
            <td>1976</td>
        </tr>
        <tr>
            <th>Location</th>
            <td>Baltimore, Maryland</td>
        </tr>
    </tbody>
</table>

上面的代码将在字符串 Established 始终采用该格式(首字母大写、无空格等)的情况下工作。
更强大的解决方案:

var year = $("th").filter(function(){
  return /^established$/i.test($.trim($(this).text()));
}).nextAll().filter(function() { // If there's more sibling TD...
  // get all that have exactly 4 numbers as text
  return /^\d{4}$/.test($.trim($(this).text()));
}).first().text(); // ...but get the first one's text.

console.log(year); // "1976"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody>
        <tr>
            <th> EstablishEd   </th> <!-- Contains spaces and possible uppercase errors? -->
            <td>1976</td>
        </tr>
        <tr>
            <th>Location</th>
            <td>Baltimore, Maryland</td>
        </tr>
        <tr>
            <th>Workers</th>
            <td>3100</td>
        </tr>
    </tbody>
</table>

https://api.jquery.com/contains-selector/
https://api.jquery.com/next/
https://api.jquery.com/text/

关于javascript - 通过邻居获取 TD 内的文本 THE 内部文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820961/

相关文章:

javascript - 如何向图表添加线条

c++ string.find() 返回字符串的长度

linux - 清空文件在查找中不起作用

javascript - 用于多绘图的 jQuery 就绪函数

jquery - 找到一件事改变另一件事

javascript event.target 在 mozilla 中不工作

javascript - 提交表单后在同一页面中显示消息

javascript - 从 javascript 函数调用 jquery

jquery - ColdFusion 9、JSON 和 jQuery EasyUI

javascript - 计算for循环中的输入文件