使用Javascript,如何访问一行的特定子行?

问题描述 投票:8回答:7

使用Javascript,我如何访问一行中的特定子行?

例如:第二 <TD><TR> 其中ID=id33322010100167

<table>
<tr id="id33322010100167">
<td>20101001</td>
<td>918</td>
<td>919</td>
<td>67</td>
<td>CAR PROBLEM</td>
</tr>
<tr id="id33322010100169">
<td>20102001</td>
<td>913</td>
<td>914</td>
<td>62</td>
<td>LUNCHTIME</td>
</tr>
<table>
javascript html-table row
7个回答
6
投票
var index = 1; // second element
var child = document.getElementById('id33322010100167').childNodes[index]

4
投票

也许你可以试试这个。

var tRow = document.getElementById("tableName").getElementsByTagName("tr");

for(var i = 0; i < tRow.length; i++){
    if(tRow[i].id == "name of your id"){
        //do something
    }
}

1
投票

最可靠的是 cells 集,它不像 childNodes 在非IE浏览器中会忽略单元格之间的空白文本节点。

var td = document.getElementById("id33322010100167").cells[1];

1
投票

我找到了这个解决方案,在结合两个最额定的一个。

你可以不使用childNodes,而是在这一行的下面用Elements of typ td来获取。

var array_td = document.getElementById('id33322010100167').getElementsByTagName("td");

要想得到第一个td的内容,你可以用:

array_td[1]

这样做的主要好处是,在数组中你不会有所有你不想处理的空白,而且如果添加了一些新的子节点(不是td),你也不必改变索引。


0
投票

使用DOM,你可以得到表,然后在子元素上迭代,同时保持计数。

当然,元素的id应该是唯一的,所以 document.getElementById('id') 作品。


0
投票

使用 jQuery:

first = $('#id33322010100167 td:first'); // gives you the first td of the tr with id id33322010100167 
last = $('#id33322010100167 td:last'); // gives you the last td of the tr with id id33322010100167 

你可以使用 next()来迭代元素。

first.next();

0
投票
<table id="studTable" class="table table-bordered">
     <thead>
        <tr>
           <td>Click</td>
        </tr>
     </thead>
     <tbody>
           <tr><td><a href="#" onclick="ClickRow(this)">Click</a></td></tr>
     </tbody>
</table>

你可以通过点击行内的rowcell来读取你选择的行,然后读取单元格的值,或者从表中删除行。

function ClickRow(r) {
        console.log(r.parentNode.parentNode.cells[0].innerHTML); //Read First Cell in Row
        var i = r.parentNode.parentNode.rowIndex;
        document.getElementById("studTable").deleteRow(i); //Remove Row
    }
© www.soinside.com 2019 - 2024. All rights reserved.