php 页面自动刷新时,使用本地存储将css .selected类名添加回html表

watbbzwu  于 2023-01-01  发布在  PHP
关注(0)|答案(1)|浏览(105)

我已经确认本地存储使用

sessionStorage.setItem(rowId, 'true');

当页面刷新时,我尝试将css.selected类名重新应用到行ID
主要目的是在重新加载页面时保持选中的行突出显示
x一个一个一个一个x一个一个二个x

--Java函数,点击时高亮显示表格行,并将行ID存储在sessionStorage.setItem中(rowId,'true');

<script type="text/javascript">
highlight_row();
function highlight_row() {

    var table = document.getElementById('display-table');
    var cells = table.getElementsByTagName('td');

    for (var i = 0; i < cells.length; i++) {
        // Take each cell
        var cell = cells[i];
        // do something on onclick event for cell
        cell.onclick = function () {
            // Get the row id where the cell exists
            var rowId = this.parentNode.rowIndex;
            var rowsNotSelected = table.getElementsByTagName('tr');
            for (var row = 0; row < rowsNotSelected.length; row++) {
                rowsNotSelected[row].style.backgroundColor = "";
                rowsNotSelected[row].classList.remove('selected');
            }
            var rowSelected = table.getElementsByTagName('tr')[rowId];
            rowSelected.style.backgroundColor = "yellow";
            rowSelected.className += " selected";
    
            sessionStorage.setItem(rowId, 'true');
            //alert(rowId);   
            
        }
    }

}
</script>
von4xj4u

von4xj4u1#

我建议更换这条线路

// that would add multiple entries per click on different rows 
// eg: 1: true, 3: true, 47: true
sessionStorage.setItem(rowId, "true");

sessionStorage.setItem('rowId', rowId);

这将覆盖上次单击的rowId的值,并且您不必检查所有可能的行/键值对。
要设置类,请使用你已经在click处理程序中编写的代码,将该代码块放在for循环之后。

// your for loop
for (var i = 0; i < cells.length; i++) { 
   ...
}

// new code
// check if rowId key exist
// if rowId does not exist null is returned - so we can check for that

if ( sessionStorage.getItem('rowId') !== null ) {
      rowSelected = table.getElementsByTagName('tr')[sessionStorage.getItem('rowId')];
      rowSelected.style.backgroundColor = "yellow";
      rowSelected.className += " selected";
}

相关问题