2010-07-23 143 views
2

我有一个网站有三个标签,我试图根据点击哪个标签动态添加鼠标悬停/鼠标悬停事件,问题是它看起来鼠标悬停/悬停事件是'绑定“到他们被调用后的标签。有没有办法从标签中“解除”事件?如何删除鼠标悬停/鼠标事件

这里是我的js是什么样子

onTab1Clicked() 
{ 
    $('#tab2').mouseover(function() { 
     $('#tab2').addClass('outlineBorder'); 
     }); 
    $('#tab2').mouseout(function() { 
     $('#tab2').removeClass('outlineBorder'); 
     }); 
    $('#tab3').mouseover(function() { 
     $('#tab3').addClass('outlineBorder'); 
     }); 
    $('#tab3').mouseout(function() { 
     $('#tab3').removeClass('outlineBorder'); 
     }); 
} 

onTab2Clicked() 
{ 
    $('#tab1').mouseover(function() { 
     $('#tab1').addClass('outlineBorder'); 
     }); 
    $('#tab1').mouseout(function() { 
     $('#tab1').removeClass('outlineBorder'); 
     }); 
    $('#tab3').mouseover(function() { 
     $('#tab3').addClass('outlineBorder'); 
     }); 
    $('#tab3').mouseout(function() { 
     $('#tab3').removeClass('outlineBorder'); 
     }); 
} 

onTab3Clicked() 
{ 
    $('#tab2').mouseover(function() { 
     $('#tab2').addClass('outlineBorder'); 
     }); 
    $('#tab2').mouseout(function() { 
     $('#tab2').removeClass('outlineBorder'); 
     }); 
    $('#tab1').mouseover(function() { 
     $('#tab1').addClass('outlineBorder'); 
     }); 
    $('#tab1').mouseout(function() { 
     $('#tab1').removeClass('outlineBorder'); 
     }); 
} 

此工程在页面加载正常,但如果我从TAB1(页面负载状态)点击转到另一个选项卡,然后回到TAB1鼠标悬停/出事件仍在灭火。

谢谢。

+2

你应该接受你的问题的答案(通过旁边的复选标记)。它将有助于在将来获得答案,并帮助下一个搜索同一问题的人找到你的问题。 – 2010-07-23 01:34:10

回答

4

你可以在这里做一些非常简单的变化总体简化你的方法。首先,将那些#tab1,#tab2#tab3元素赋予一个类,例如, class="tab"那么你可以这样做:

$(".tab").click(function() { 
    $(this).addClass('active'); //make this tab active 
    $(".tab").not(this).removeClass('active'); //make other tabs inactive 
}); 

现在,当您单击任一选项卡,它就会“主动”类,而其他人将不会拥有它。然后你可以使用.live():not() selector得到你想要的悬停效果,像这样:

$('.tab:not(.active)').live('mouseover mouseout', function() { 
    $(this).toggleClass('outlineBorder'); 
}); 

这个选择不会在标签作用,而它的.active,所以悬停效果才能体现出来的标签上不是选择,就像你原来的那样,但更容易维护。

+1

+1大量的代码缩减,没有绑定/解除绑定,聪明地使用'.live )',我会说你只是覆盖了基地。 :O) – user113716 2010-07-23 02:11:01

0

是的,你差点没有了!

$('#tab3').unbind('mouseout'); 
1
$('#tab1,#tab2,#tab3').click(function(){ 
    $(this).unbind('mouseout mouseover'); 
    // this will unbind mouseout and mouseover events when click 
    // e.g. onTab1Clicked, mouseout and mouseover events will be unbind on tab1 
}) 
+0

你也可以通过多个事件调用'.unbind()',例如'.unbind('mouseout mouseover')' – 2010-07-23 01:25:09

+0

啊,我不确定那个尼克,谢谢你帮我清理它;;) – Reigel 2010-07-23 01:26:32