爬上DOM树

时间:2013-07-14 19:34:52

标签: javascript jquery html-table

如果我知道要读取哪一行,如何读取特定列中的所有td个单元格。

让我说明一下:

<tr>
    <td><input type="checkbox" value="0"></td>
    <td>1</td>
    <td>John</td>
    ....
</tr>

在某些时候,我知道我需要读取值0,并且我想知道该行中的所有其他td

所以在某个循环中我有这个:

selected[i][0]

给了我:<input type="checkbox" value="0"> var i来自0

如何获得所有物品?

我尝试过:$('tr').eq(i).find('td').eq(1).text()

并没有给我正确的价值观。

5 个答案:

答案 0 :(得分:2)

Protip:学习使用强大的Firebug控制台获取所选元素的直接输出 - 这是直观代码的方式Javascript: - )

$('tr').eq(i).children('td').children('input').val() 
也许,但轮到你了。

enter image description here

答案 1 :(得分:1)

请查看以下helpshttp://jsfiddle.net/sLBgY/

<script>
    function load(){
        var table = document.getElementById("mtable");
        for (var i = 0, row; row = table.rows[i]; i++) {
           if(table.rows[i].cells[0].getElementsByClassName('valTd')[0].value==0){
               for (var j = 1, col; col = row.cells[j]; j++) {
                 alert(table.rows[i].cells[j].innerText);
               } 
            }
        }
    }
</script>

<body onload="load()">
<table id="mtable">    
    <tr>
        <td><input class='valTd' type="checkbox" value="0"></td>
        <td>1</td>
        <td>John</td>
   </tr>
   <tr>
        <td><input class='valTd' type="checkbox" value="1"></td>
        <td>1</td>
        <td>John</td>
   </tr>
 </table>
 </body>

答案 2 :(得分:0)

如果您的HTML看起来像这样

<tr>
    <td><input type="checkbox" value="0"></td>
    <td>1</td>
    <td>John</td>
</tr>

<tr>
    <td><input type="checkbox" value="0"></td>
    <td>2</td>
    <td>Julie</td>
</tr>

那么你只需要这样做

   $('tr').each(function( index, element) {
      var $element = $(element),
          checkbox = $element.children(0)[0];
          id = $element.children(1); 
          name = $element.children(2);
   });
  

<强> Demo Link

答案 3 :(得分:0)

这将找到正确行中的所有单元格:

$(function () {
    var found = false;
    $('table tr').each(function () {
        var cells = $(this).children('td');
        if (cells.eq(0).find('input').val() == 0) { // the value you're looking for
            found = cells;
        }
    });
    if (found) {
        alert(found.eq(0).html() + found.eq(1).html() + found.eq(2).html());
    }
});

http://jsfiddle.net/7VmR9/16/

答案 4 :(得分:0)

  

在某些时候我知道我需要读取值0并且我想知道   该行中的所有其他td。

如果我理解正确,这应该使用jQuery库为您提供预期的结果:

$("td input[value='0']").parent().parent().children("td").each(function(){
    alert($(this).text()); //Replace alert with however you want to output your data
});

<强>解释

$("td input[value='0']")将选择属性<input />设置为0的所有value代码,包含在<td>代码

.parent()将转到父<td>代码

.parent()将转到父<tr>代码

.children("td")会选择相应<td>代码中包含的所有tr代码

.each(function(){...})将对这些<td>代码执行某些操作

$(this).text()将选择<td>的文字