码迷,mamicode.com
首页 > Web开发 > 详细

js 操作table

时间:2018-03-15 16:25:29      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:body   index   tno   函数   tab   长度   div   innertext   gpo   

    <script>
        function getColumnDetail(column) {
            column.style.color = "blue"; //将被点击的单元格设置为蓝色
            //alert(column.innerHTML); //弹出被点单元格里的内容
            //单击单元格 td追加里面intput
            console.log(column.parentNode.rowIndex);//获取行所在的索引
            getRowstd(column.parentNode.rowIndex);
            console.log(column.cellIndex); //获取列所在的索引
        };
        function setTable(trLineNumber, trColumn) {
            var _table = document.getElementById("table"); //获得tbody对象
            var _row;
            var _cell;
            for (var i = 0; i < trLineNumber; i++) { //获取传递过来的行数
                _row = document.createElement("tr"); //创建元素tr
                _table.appendChild(_row); //table下追加这个元素

                for (var j = 0; j < trColumn; j++) {  //根据传递过来的字符串长度或其他
                    _cell = document.createElement("td"); //创建元素td
                    _cell.onclick = function () { getColumnDetail(this) }; //为每个单元格增加单击事件
                    _cell.innerText = "000"; //元素的内容
                    _row.appendChild(_cell); //tr下面追加这个td
                }
            }
        }
        function load() {
            var tab = document.getElementById("table");
            var rows = tab.rows; //获取表格的行数

            for (var i = 0; i < rows.length; i++) { //遍历表格的行

                for (var j = 0; j < rows[i].cells.length; j++) {  //遍历每行的列
                    console.log(rows[i].cells[j].innerHTML); //输出单元格内容
                }
            }
        }
        function getRowstd(rowIndex) {  //返回指定行下的所有td内容
            var tab = document.getElementById("table");
            var rows = tab.rows; //获取表格的行数
            for (var i = 0; i < rows[rowIndex].cells.length; i++) {
                console.log(rows[1].cells[i].innerHTML + "\r"); //输出单元格内容
            }
        }

        window.onload = function () {
            setTable(5, 5);
            load();//函数调用
        }
    </script>

 

js 操作table

标签:body   index   tno   函数   tab   长度   div   innertext   gpo   

原文地址:https://www.cnblogs.com/enych/p/8573901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!