【问题标题】:Highlight multiple rows with specific ID's突出显示具有特定 ID 的多行
【发布时间】:2016-11-18 02:36:04
【问题描述】:

寻找解决方案以突出显示表格中的 <td> 元素,并在悬停时使用特定 ID。

我的代码

    $('#orderstable').hover(function()
    {
        $('#id_1').find('td').addClass('hover');
    }, function()
    {
        $('#id_1').find('td').removeClass('hover');
    });
#orderstable td
{ 
    padding:0.7em;
    border:#969696 1px solid;
}

.hover
{
    background:yellow;
}
<table id="orderstable">
<thead>
    <tr>
        <th>Proces</th>
        <th>Step 1</th>
        <th>Step 2</th>
        <th>Step 3</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Proces 1</td>
        <td id='order_2'>job 2</td>
        <td id='order_1'>job 1</td>
        <td id='order_3'>job 3</td>
    </tr>
    <tr>
        <td>Proces 2</td>
        <td id='order_3'>job 3</td>
        <td id='order_4'>job 4</td>
        <td id='order_1'>job 1</td>
    </tr>
</tbody>
</table>

我想要实现的是,当您将鼠标悬停在 id='order_1' 的 td 单元格上时,它会突出显示此 &lt;TD&gt; 以及其他 id='order_1' 的 td。
当然,对于其他 id(order_2、order_3 等),我需要相同的功能。

有什么想法吗?

【问题讨论】:

  • Id 必须是唯一的 .... 改用类名
  • id 相同的项目之间是否存在奇点?也许是为了避免使用无用的类名
  • 请检查我更新的小提琴,我之前的小提琴有误。

标签: jquery html highlight


【解决方案1】:

我建议改用类,但是要回答您的问题,您可以通过使用第 n 个子 css 伪来实现。

我在这里创建了一个快速的 JSFiddle 作为示例。 https://jsfiddle.net/fzjuxyeL/8/ - 更新工作!

#order_1:nth-child(1n+1)
// Start at 1 and increment by 1 finding all divs with ID

$('#order_1:nth-child(1n+1)').hover(function(){
    $('#order_1:nth-child(1n+1)').toggleClass('toggled')
});
// Applies class to all divs with specified ID when hovered

【讨论】:

  • 这仅在您将鼠标悬停在相应 ID 的第一项上时才有效。
  • 嗨,太好了,刚刚用类替换了 id,这正是我正在寻找的!
  • @QuangdaoNguyen 抱歉,我没有注意到,但是我找到了一个修复程序并更新了它,希望对您有所帮助
【解决方案2】:

ID 必须是唯一的。你应该使用类。 IE。 class="order1"$('.order1').addClass(...)。此外,您的 JS 还差得很远,因为您正在选择不存在的项目,并将目标定位在这些选择器中的 tds inside,而不是 tds 本身。为了实现你的目标,我会做这样的事情:

$('#orderstable').on('mouseover', 'td', function() {
    var elemClass = this.className
        .split(' ') // Gets array of classes
        .filter(function(item) {
            return item.match(/order_\d/) || false;
        }) // Filter down to classes matching 'order_[NUMBER]'
        .pop(); // Get the class. (Actually gets the last item in an array that contains only one item, so same thing.)
    $('.' + elemClass).addClass('hover');
}).mouseout(function() {
    $(this).find('td').removeClass('hover');
});

Here's a JSFiddle demonstrating this.

实际上,您还可以对每个单独的班级执行以下操作:

$('.order_1').hover(function() {
    $('.order_1').toggleClass('hover');
});

但我决定“自动化”这个。

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 2012-08-06
    • 2012-04-04
    • 2012-10-02
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多