找到表行内的元素

时间:2014-09-06 17:35:37

标签: jquery html-table

如何使用jQuery我可以获取此表的内容:

<table>
  <tr>
    <th>Element 1</th>
    <td>Red</td>
  </tr>
  <tr>
    <th>Element 2</th>
    <td>Pink</td>
  </tr>
</table>

我想找到第Element 1行的颜色。我不需要.each就像我想要的颜色一样。


我试过了:

var color = find("<th>Element 2</th>").next().("<td>").html();

5 个答案:

答案 0 :(得分:1)

如果您需要元素列表(即颜色),则无法避免循环.each。你可以举例如:

$("table tr td:last-child").each(function(k,v) {
   alert( $(v).html() );
});

或:

var colors = $("table tr td:last-child");
for(var x=0;x<colors.length;x++) {
   alert( $(colors[x]).html() );
}

但这不是一个好的方法,因为你的细胞真的无法识别(等等idclass)。如果更改了表结构,则当前的javascript无法正常工作。我建议在您的可检索信息后命名,如下所示:

<table>
  <tr>
    <th>Element 1</th>
    <td class="color">Red</td>
  </tr>
  <tr>
    <th>Element 2</th>
    <td class="color">Pink</td>
  </tr>
</table>

$("table tr td.color").each(function(k,v) {
   alert( $(v).html() );
});

或:

var colors = $("table tr td.color");
for(var x=0;x<colors.length;x++) {
   alert( $(colors[x]).html() );
}

<强>更新

刚看到你只想要第一种颜色。只需使用以下内容:

var color = $("table tr:first-child td:last-child").html();

如果您真的想在<th>中按文字搜索,请检查:

var color = $("table tr th:contains('Element 1')").next().html();

答案 1 :(得分:0)

使用:

var color=$('th:contains(Element 1)').next().text()

<强> Working Demo

答案 2 :(得分:0)

使用类似的东西,我已经测试过并且正在使用。

    <script>
        $().ready(function(e){
            $("table tr td").each(function(e){
                alert($(this).html());
            })
        })
    </script>

答案 3 :(得分:0)

var color ;
$("table td").each(function(){
color=$(this).html();
});

答案 4 :(得分:0)

假设您需要多次使用这些值,最好从值中创建一个对象。像这样:

var colors = {};
$('tr').each(function(){
    colors[($('th',this).html())] = $('td',this).html();
});

尝试http://jsfiddle.net/asvvd4rh/