簡體   English   中英

如何使用JavaScript顯示/隱藏隱藏的HTML表行(沒有jQuery)

[英]How to show/hide hidden HTML table rows using JavaScript (no jQuery)

編輯:這已在下面得到解答。

我想有一個HTML表,每行之間有隱藏的行,有關頂級行的更多信息。 單擊第一列中的展開/折疊圖像鏈接時,隱藏行的可見性將從display:none切換; 顯示:table-row;。 我有一段時間沒有編寫JavaScript,需要能夠在JavaScript中嚴格執行此操作,並且不能使用jQuery toggle()方法。

我如何使用JavaScript來查找帶有class =“parentRow”的class =“subRow”的兄弟,該按鈕位於表中,然后切換該兄弟行的可見性?

HTML

<table style="width:50%">
    <caption>Test Table</caption>
    <thead>
        <tr align="center">
            <th><span class="offscreen">State Icon</span></th>
            <th>Column 2</th>               
            <th>Column 3</th>               
            <th>Column 4</th>               
            <th>Column 5</th>
        </tr>
    </thead>
    <tbody>
        <tr align="center" class="parentRow">
            <td><a href="#" onclick="toggleRow();"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
            <td>test cell</td>
            <td>test cell</td>
            <td>test cell</td>
            <td>test cell</td>
        </tr>
        <tr style="display: none;" class="subRow">
            <td colspan="5"><p>Lorem ipsum dolor sit amet...</p></td>
        </tr>
....
    </tbody>
</table>

CSS

.offscreen {
  position: absolute;
  left: -1000px;
  top: 0px;
  overflow:hidden;
  width:0;
}

.subRow {
    background-color: #CFCFCF; 
}

JavaScript的

function toggleRow() {
    var rows = document.getElementsByClassName("parentRow").nextSibling;
    rows.style.display = rows.style.display == "none" ? "table-row" : "none";
}

傳遞事件處理程序對使用this單擊的行的引用:

<td><a href="#" onclick="toggleRow(this);"><img alt="Expand row" height="20px;" src="expand.png"></a></td>

然后更新您的toggleRow函數,如下所示:

function toggleRow(e){
    var subRow = e.parentNode.parentNode.nextElementSibling;
    subRow.style.display = subRow.style.display === 'none' ? 'table-row' : 'none';    
}

您可能需要考慮創建一個通用函數來向上導航DOM樹(這樣,當您/更改HTML時,此函數不會中斷)。

使用id屬性來獲取元素而不是類,並在其id中為任何行賦予唯一的數字,以使它們不同。

<tr style="display: none;" class="subRow" id="subRow1">
.
.
.
<tr style="display: none;" class="subRow" id="subRow2">
.
.
<tr style="display: none;" class="subRow" id="subRow3">

這對我有用:

function toggleRow() {
    var row = document.getElementsByClassName("parentRow")[0];
    var next = row.parentNode.rows[ row.rowIndex ];
    next.style.display = next.style.display == "none" ? "table-row" : "none";
}

暫無
暫無

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

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