簡體   English   中英

如何顯示HTML表中的一行並更改為下一行?

[英]How to display one row from a HTML table and change to next?

我有2列5行的HTML表。

你可以這樣做:

function findMyRow(el)(){
    if(!el.parentNode) return null;
    else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
    else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
    tbl.rows[i].onclick = function(e){
        var selectedRow = null;
        if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
        selectedRow = findMyRow(e.target);
        //this is just for preventing false event raising
        if(!selectedRow) return false;
        var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
        for(car j=0;j<selectedRow.cells.length;j++){
            var cell = selectedRow.cells[j];
            //let's say your inputs each has an unique ID based on your columns index
            //like <input id="cellData0" ttype="text" />
            //or <input id="cellData1" ttype="text" /> and so on
            document.getElementById("cellData" + j).value = cell.innerText;
        }
    }
}

盡管您可以比使用jQuery更輕松地完成此操作。

使用Jquery,您可以執行以下操作:

$(document).ready(function(){
    window.rowIndex = 0; // gobal variable

    function displayRow(){
        var tableRows = $('#mytable tr');
        if(tableRows.length <= window.rowIndex) {
            window.rowIndex = 0;
        }
        var rowCells = $(tableRows[window.rowIndex]).find('td');
        $('.cellone').val($(rowCells[0]).html());
        $('.celltwo').val($(rowCells[1]).html());
        window.rowIndex = window.rowIndex + 1;
    };

    $('.next').click(function(event){ displayRow(); });
    displayRow();
});

這里有一個現場演示希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM