jquery:根据具有多个类的元素中的一个类设置变量

时间:2009-09-02 15:47:00

标签: jquery class variables

我正在尝试制作一个在悬停时突出显示列和行的表格(我意识到那里有jquery插件可以做到这一点,但我正在努力学习,所以我想要做的就是它本身。)

这是我到目前为止所得到的:

$('th:not(.features), td:not(.features)').hover(highlight);

 function highlight(){
     $('th.highlightCol, td.highlightCol').removeClass('highlightCol');
     var col = $(this).attr('class');
     $('.' + col).addClass('highlightCol');
 };

 $('tr').hover(highlightRowOn, highlightRowOff);

 function highlightRowOn(){
     $(this).children('td:not(.highlightCol)').addClass('highlightRow');
 };

 function highlightRowOff(){
     $(this).children('td:not(.highlightCol)').removeClass('highlightRow');
 };

除了一个问题外,这种方式还可以:
每个'td'都有一个特定于它的列(package1,package2,package3,package4)。正是这种情况被传递给变量(col),以便在其中一个'td'悬停时将类'highlightCol'添加到列中。

但是,如果将光标移动到突出显示的行的新列,则您登陆的“td”有两个类(highlightedRow和package *)。这些都被传递给变量,因此新列没有收到要突出显示的正确类。

有没有办法让我只定位'package *'类并将其传递给变量而忽略'highlightedRow'类?

我希望有人能够理解并且非常感谢所提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

  

我有没有办法定位   'package *'类并将其传递给   变量而忽略了   'highlightedRow'类?

是的,使用优质的'老式DOM。由于您正在学习,我不会明确地给出解决方案。

最简单的方法是从jQuery获取HTMLElement:$('.selector').get(0)返回第一个匹配的元素。然后使用元素的className属性来获得你想要的东西。

此外,this selector可能有用。

答案 1 :(得分:0)

感谢您的帮助......终于明白了。这是感兴趣的代码。

$('th:not(.features), td:not(.features)').hover(highlight, remove);

function highlight(){
    $(this).removeClass('highlightRow');
    var col = $(this).attr('class');
    $('.' + col).addClass('highlightCol');
};

function remove (){
    $('th.highlightCol, td.highlightCol').removeClass('highlightCol');
    $(this).addClass('highlightRow');
};

$('tr').hover(highlightRowOn, highlightRowOff);

function highlightRowOn(){
    $(this).children('td:not(.highlightCol), th:not(.highlightCol)').addClass('highlightRow');
};

function highlightRowOff(){
    $(this).children('td:not(.highlightCol), th:not(.highlightCol)').removeClass('highlightRow');
};