javascript - 如何使用 js 或 jquery 在单击时突出显示 html 表中的列?

标签 javascript jquery html

我正在尝试实现一个 javascript,它将在单击时突出显示 html 表中的列。作为下面行突出显示的工作示例,我尝试将其与 table.columns 一起使用,但 table.columns 不存在。是有没有使用 jquery 突出显示 html 表中的列?

高亮行的工作代码: 表格突出显示 POC

        <script>

            function highlight() {
                var table = document.getElementById('dataTable');
                for (var i = 0; i < table.rows.length; i++) {
                    table.rows[i].onclick = function () {
                        if (!this.hilite) {
                            this.origColor = this.style.backgroundColor;
                            this.style.backgroundColor = '#BCD4EC';
                            this.hilite = true;
                        }
                        else {
                            this.style.backgroundColor = this.origColor;
                            this.hilite = false;
                        }
                    }
                }
            }

        </script>
        <style>


            table {
                border-spacing: 0px;
            }

            td {
                border: 1px solid #bbb;
                padding: 0.2em;
            }
        </style>
    </head>
    <body>
        <table id="dataTable">
            <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
            <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
            <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
        </table>
    </body>
</html>

最佳答案

您可以使用以下代码:

$('td').on('click', function() {
    var $currentTable = $(this).closest('table');
    var index = $(this).index();
    $currentTable.find('td').removeClass('selected');
    $currentTable.find('tr').each(function() {
        $(this).find('td').eq(index).addClass('selected');
    });
});

只需将它放在您的 JS 文件中,它就会独立地处理所有可用的表。如果您只想在特定表上使用它,只需将初始选择器更改为 $('#myTable td')

另外不要忘记添加 .selected{ background-color: #ace; 你的 css 文件中的类。

这是 working example .

干杯!

关于javascript - 如何使用 js 或 jquery 在单击时突出显示 html 表中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131000/

相关文章:

javascript - jQuery 发送并显示每行文本区域的 ajax 结果

javascript - Adobe Acrobat Pro DC JavaScript 字段属性未传播

javascript - 将数据或数组索引附加到 anchor 标记

javascript - JQuery 无法使用 hover() 方法识别数据表的 'tbody' 和 'tr'

javascript - 单击图像时如何添加图像

html - 如何使按钮中的图标居中

javascript - IE 上没有图像只有带白色 x 的黑框

html - 在 firefox 开发人员控制台中更改 css 属性

javascript - 无论它在 DOM 中的什么位置,我怎样才能使用 jquery 获取下一个/上一个链接?

javascript - 表排序器 : table. config.parsers[c] 未定义