如何获取可能定义或不定义的表格单元格的Javascript集合

时间:2012-11-23 14:27:48

标签: javascript dom

  

可能重复:
  Checking existence of properties in JavaScript

我试图在不使用jQuery的情况下获取表格的tbody单元格(i.e. this.tBodies[0].rows[0].cells)的第一行。如果没有,我不希望导致错误。 以下似乎有效,但有更好的方法吗?

var tbody_cells = (this.tBodies
  && this.tBodies
  && this.tBodies[0].rows
  && this.tBodies[0].rows[0])
? this.tBodies[0].rows[0].cells
:undefined;

3 个答案:

答案 0 :(得分:2)

您可以使用querySelectorAll

this.querySelectorAll('tr:first-child td');

这对IE7无效,但你真的关心吗?

如果您关心并且经常需要做这类事情,我建议您使用实用程序库,即jQuery,这样可以轻松解决许多兼容性问题:

$('tr:first-child td', this);

答案 1 :(得分:2)

使用try catch块:

var result;
try{
result = this.tBodies[0].rows[0].cells;
}catch(e if e instanceof ReferenceError){
result = undefined;
}

答案 2 :(得分:0)

实际上我不知道桌子是否随时可用。

<html>
<body>
    <table id="tbl">
        <tbody>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

function getTblCells() {

    var cells = document.getElementById("tbl").children[0].children[0].children;

    return children ? children : [];
}

你也可以给第一行一个id并检查一行是否存在(如果你怀疑它存在),然后进行'有孩子'检查。