javascript遍历表

定义表结构

1. 通过id遍历

<html>
<body>

<table id="tb" border="1">
<tr>
    <td>row1,cell1</td>    <td>row1,cell2</td>
</tr>

<tr>
    <td>row2,cell1</td>    <td>row2,cell2</td>
</tr>

<tr>
    <td>row3,cell1</td>    <td>row3,cell2</td>
</tr>
</table>
<button type="button" onclick="f()">click me</button>

<script>
function f()
{
    var t=document.getElementById("tb");
    if (t)
    {
        for(var i=0; i< t.rows.length; i++)
        {
            for(var j=0; j<t.rows[i].cells.length; j++)
            {
                alert(t.rows[i].cells[j].innerText);
            }
        }
    }
}
</script>

</body>
</html>

2. 通过jQuery遍历

<html>
<head>
<meta charset="utf-8">
</head>
<body>


<table class="tb" border="1">
<tr>
    <td>row1,cell1</td>    
    <td>row1,cell2</td>
</tr>

<tr>
    <td>row2,cell1</td>    
    <td>row2,cell2</td>
</tr>

</table>

<script type="text/javascript" src="./js/jquery-1.11.1.min.js"></script>

<script>
$(document).ready(function(){
        $("td").each(function(){
            alert($(this).text());
        })
})
</script>

</body>
</html>

添加按钮,按按钮时弹出

<html>
<head>
<meta charset="utf-8">
</head>
<body>


<table class="tb" border="1">
<tr>
    <td>row1,cell1</td>    
    <td>row1,cell2</td>
</tr>

<tr>
    <td>row2,cell1</td>    
    <td>row2,cell2</td>
</tr>

</table>
<button type="button">click me</button>

<script type="text/javascript" src="./js/jquery-1.11.1.min.js"></script>

<script>
$(document).ready(function(){
        $("button").click(function(){
            $("td").each(function(){
                alert($(this).text());
            })
        })
})
</script>

</body>
</html>

 

posted @ 2015-06-21 18:15  jihite  阅读(867)  评论(1编辑  收藏  举报