2010-07-23 144 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