如何使用jQuery过滤器选择器查找表标记td值

时间:2016-04-19 04:43:17

标签: javascript jquery html

<table>
    <tr>
        <td>Calories </td>
        <td>TargetValue1</td>
    </tr>
    <tr>
        <td>Protein</td>
        <td>TargetValue2</td>
    </tr> 
    <tr>
        <td>Protein</td>
        <td>TargetValue3</td>
    </tr> 

如何选择所有第二个td 值?

我试过

    $.each($("#nutritab tbody tr td:eq(1)"),function(i , item){
        alert($(item).text());  
    });

但只返回第一个值。

3 个答案:

答案 0 :(得分:3)

  

使用nth-child选择器代替:eq(index)

:nth-child(n)选择器匹配每个元素,即nth child()Index starts from 1

:eq(index)选择器会在匹配集中的索引n处选择元素。(Zero-based index

$.each($("#nutritab tr td:nth-child(2)"), function(i, item) {
  alert($(item).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='nutritab'>
  <tr>
    <td>Calories</td>
    <td>TargetValue1</td>
  </tr>
  <tr>
    <td>Protein</td>
    <td>TargetValue2</td>
  </tr>
  <tr>
    <td>Protein</td>
    <td>TargetValue3</td>
  </tr>
</table>

答案 1 :(得分:1)

&#13;
&#13;
$.each($("#nutritab tbody tr"), function(i, item) {
  alert($(this).find('td:nth-child(2)').text());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='nutritab'>
  <tr>
    <td>Calories</td>
    <td>TargetValue1</td>
  </tr>
  <tr>
    <td>Protein</td>
    <td>TargetValue2</td>
  </tr>
  <tr>
    <td>Protein</td>
    <td>TargetValue3</td>
  </tr>
&#13;
&#13;
&#13;

  1. 首先将id命名为表
  2. 使用。nth-child() 注意:从1
  3. 开始

答案 2 :(得分:1)

您可以使用nth child() of selector选择器,它匹配$('.tb').each(function(index, tr) { alert($(this).find('td:nth-child(2)').text()); });的每个元素:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="tb">
  <tr>
        <td>Calories </td>
        <td>TargetValue1</td>
    </tr>
    <tr>
        <td>Protein</td>
        <td>TargetValue2</td>
    </tr> 
    <tr>
        <td>Protein</td>
        <td>TargetValue3</td>
    </tr> 
</table>
&#13;
$env = $injector->make(Env::class);
$paths = array(__DIR__.'/../');
$isDevMode = isset($enf['DEVELOPMENT']);

// the connection configuration
$dbParams = array(
    'driver' => 'pdo_mysql',
    'host' => $env['DB_HOST'],
    'user' => $env['DB_USER'],
    'password' => $env['DB_PASS'],
    'dbname' => $env['DB_NAME'],
);

$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
&#13;
&#13;
&#13;