复制代码
<!DOCTYPE html>
<html>
<head>
    <style>
        .highlight {
            background-color: #ffeb3b; /* 黄色背景 */
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        td, th {
            border: 1px solid #ddd;
            padding: 8px;
        }
      #mytr{background-color: #aaeb3b;}
    </style>
</head>
<body>
    <table id="myTable">
        <tr>
            <td><input type="radio" name="rowSelect"></td>
            <td style="background-color: #ec638a;" >行1 - 数据1</td>
            <td>行1 - 数据2</td>
        </tr>
        <tr >
            <td><input type="radio" name="rowSelect"></td>
            <td>行2 - 数据1</td>
            <td>行2 - 数据2</td>
        </tr>
        <tr>
            <td><input type="radio" name="rowSelect"></td>
            <td>行3 - 数据1</td>
            <td>行3 - 数据2</td>
        </tr>
        <tr>
            <td><input type="radio" name="rowSelect"></td>
            <td>行4 - 数据1</td>
            <td>行4 - 数据2</td>
        </tr>
    </table>

    <script>
        // 获取所有单选按钮
        const radios = document.querySelectorAll('input[type="radio"]');
        
        // 为每个单选按钮添加事件监听
        radios.forEach(radio => {
            radio.addEventListener('change', function() {
                // 移除所有行的高亮样式
                document.querySelectorAll('#myTable tr').forEach(row => {
                    row.classList.remove('highlight');
                });

                // 如果当前单选按钮被选中,则为其所在行添加高亮样式
                if (this.checked) {
                    this.closest('tr').classList.add('highlight');
                 // this.style.backgroundColor = 'yellow'; // 设置黄色背景
                }
            });
        });

        // 初始化检查(处理页面加载时已选中的情况)
        document.querySelectorAll('input[type="radio"]:checked').forEach(radio => {
            radio.closest('tr').classList.add('highlight');
        });
    </script>
</body>
</html>
复制代码