Catch cell值指定带有jquery的HTML表

时间:2014-06-15 20:17:03

标签: javascript jquery html

我需要获取 <tr> 的内容,其中第一个 <td> 等于&#34; 4&#34;在第三个文本框中。在这种情况下出现数字&#34; 2099451&#34;在文本框中。

  <table id="tableHtml">
    <tr>
        <td>rank</td>
        <td>place</td>
        <td>population</td>
        <td>lat</td>
        <td>lo</td>
    </tr>
    <tr>
        <td>1</td>
        <td>New York city</td>
        <td>8175133</td>
        <td>40.71455</td>
        <td>-74.00712</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Los Angeles city</td>
        <td>3792621</td>
        <td>34.05349</td>
        <td>-118.24532</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Chicago city</td>
        <td>2695598</td>
        <td>45.37399</td>
        <td>-92.88875</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Houston city</td>
        <td>2099451</td>
        <td>41.337462</td>
        <td>-75.73362</td>
    </tr>
    <tr>
        <td>5</td>
        <td>Philadelphia city</td>
        <td>1526006</td>
        <td>37.15477</td>
        <td>-94.48611</td>
    </tr>
    <tr>
        <td>6</td>
        <td>Phoenix city</td>
        <td>1445632</td>
        <td>32.46764</td>
        <td>-85.00082</td>
    </tr>
    <tr>
        <td>7</td>
        <td>San Antonio city</td>
        <td>1327407</td>
        <td>37.706576</td>
        <td>-122.44061</td>
    </tr>
    <tr>
        <td>8</td>
        <td>San Diego city</td>
        <td>1307402</td>
        <td>37.707815</td>
        <td>-122.46662</td>
    </tr>
    <tr>
        <td>9</td>
        <td>Dallas city</td>
        <td>1197816</td>
        <td>40.636</td>
        <td>-91.16830</td>
    </tr>
    <tr>
        <td>10</td>
        <td>San Jose city</td>
        <td>945942</td>
        <td>41.209716</td>
        <td>-112.00304</td>
    </tr>

</table>

我尝试使用以下代码执行此操作:

var table = $('#tableHtml');

var value = $(table).find('tr').filter(function(){ 
    return $(this).children('td').eq(2).text() == 4;
});

$('#GetValue').val(value);

Code in JSFidlle

谢谢!

2 个答案:

答案 0 :(得分:2)

你可以这样做:

$('#GetValue').val($('#tableHtml td:nth-child(1):contains("4")').next().next().text());

<强> jsFiddle example

另一种选择是:

var value = $('#tableHtml td:nth-child(1)').filter(function () {
    return $(this).text() === '4';
}).next().next().text()
$('#GetValue').val(value);

<强> jsFiddle example

答案 1 :(得分:1)

var table = $('#tableHtml');

var value = $(table).find("tr").eq(4).find("td").eq(2).text();

$('#GetValue').val(value);