通过相邻的TH内部文本获取TD内的文本

时间:2016-08-08 03:39:01

标签: javascript jquery find

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

示例:

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

我想通过搜索“已建立”来获得1976年(使用jQuery) tr / order的位置始终不变。

可能的?

2 个答案:

答案 0 :(得分:3)

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将始终采用该格式(First-uppercase,no spaces等)。
更强大的解决方案:

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/

答案 1 :(得分:2)

是的,有可能。 jQuery的.filter(callback)方法可用于根据内容过滤元素。

  • 选择th元素
  • 将选定的th元素过滤为只有“已建立的”元素
  • 选择跟随这些td元素
  • th元素

var years = $("th").filter(function() { //Get th elements that has "Established" as their text
  return $(this).text() === "Established";
}).next("td"); //Get td elements that are next to these th elements;

console.log(years.text());
<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>