2010-03-10 260 views
1

它是什么,我做错了这里:未定义id属性

当我尝试使用getttribute [“身份证”]方法的TableCell的对象,我从得到通过遍历表行/细胞则返回undefined:

var rows = document.getElementById["table"].rows; 
var cells; 
for(var i=0; i < rows.length; i++) { 
cells = rows[i].cells 
for(var j=0; j < cells.length; j++) { 
    alert(cells[j].innerHTML); //returns Cell1 
    alert(cells[j].getAttribute["id"]); //returns undefined 
    alert(document.getElementById["c1"].innerHTML); //returns Cell1 

} 
} 

这是例如HTML:

<table id="table"> 
    <tbody> 
     <tr> 
     <td id="c1">Cell1</td> 
     </tr> 
    </tbody> 
</table> 

问题是为什么没有定义的所有属性磨片getAttribute方法返回n通过单元格[j]访问?

回答

1

getAttribute是一个方法,你使用它作为一个索引

使用

alert(cells[j].getAttribute("id")); 

而且取代

document.getElementById["table"].rows; 

document.getElementById("table").rows; 

document.getElementById["c1"].innerHTML 

document.getElementById("c1").innerHTML 

getElementById也是一种方法。

0

我不知道为什么,但getAttribute不喜欢id属性。改为使用cells[j].id

0

只需使用单元格[j] .id获取单元格的标识。

1

您使用方括号[]而不是括号()在调用getElementByIdgetAttribute

//change 

getElementById["table"] 
getAttribute["id"] 
getElementById["c1"] 

//to 

getElementById("table") 
getAttribute("id") 
getElementById("c1") 

//Respectively. 
+0

是的,这是真的,这是一种方法!谢谢 – 2010-03-10 06:29:33

0

或者您可以使用getAttribute方法:

xmlDoc.getElementsByTagName("sec")[0].getAttribute("id") 

在这里,我会回来的s1<sec id="s1">这样的标签。