2012-02-14 67 views
0

如果某個元素沒有定義一個css類,我想阻止兩個事件被監視到一個元素(mouseenter和mouseleave是特定的)。Jquery不像預期的那樣使用.not和.on

該系統的流動是

  1. 在文件準備好了,我想補充.selected到#menu_top_option_1元素

    $("#menu_top_option_1").addClass("selected"); 
    
  2. 類沒有爲這兩個事件傳感器

    $("#menu_top_option_1").not(".selected").on({ 
        mouseenter: function(){ 
         $(this).addClass("highlighted"); 
        }, 
        mouseleave: function(){ 
         $(this).removeClass("highlighted"); 
        } 
    }); 
    
  3. 當發生點擊事件時,我添加class .selec綁定到#menu_top_option_1元素。

    $("#menu_top_option_1").click(function() { 
        $("#menu_top_arrow_img").animate({left: position_menu_top_option_1+'px'}, 500); 
        $(this).removeClass("highlighted"); 
        $("#option_wrapper div.option").removeClass("selected"); 
        $(this).addClass("selected"); 
    }); 
    

的問題:如預期這不起作用。即使在添加.selected之後,元素仍然具有與分配.selected之前相同的懸停事件。除了#menu_top_option_1元素外,因爲我懷疑它確實在文檔準備好時添加了該類。

有什麼建議嗎?

回答

3

您應該將事件處理程序綁定到所有的元素,然後將該事件處理中,請檢查是否被點擊當前元素具有selected類:

$(function() { 
    //bind a click event handler to all of the menu items that: 
    //1. removes the `selected` class from the element that currently has it 
    //2. applies that class to the element clicked 
    //3. removes the `highlighted` class from the current element since it will have it, due to the fact that you have to hover over an element to click it 
    $('#option_wrapper').children().on('click', function() { 
     $(this).siblings('.selected').removeClass('selected').end().removeClass('highlighted').addClass('selected'); 

    //bind a mouseenter event handler to the menu items that updates the currently moused-over element only if it doesn't have the `selected` class 
    }).on('mouseenter', function() { 

     //notice the `!` here, so we are checking for the non-existence of the class in question 
     if (!$(this).hasClass('selected')) { 
      $(this).addClass('highlighted'); 
     } 

    //bind a mouseleave event handler to the menu items that removes the `highlighted` class 
    }).on('mouseleave', function() { 
     $(this).removeClass('highlighted'); 
    }); 
}); 
​ 

這裏是一個演示:http://jsfiddle.net/g8W4z/

有些文檔:

+0

謝謝!我現在意識到,我的做法非常蠻橫。無論如何,我真的很感謝這個努力和完美的例子! – 2012-02-14 16:57:29

1

我覺得從一個事實,即你在文件準備安裝的事件偵聽器的問題造成的。一旦他們連接,你永遠不會刪除它們。因此,菜單選項的行爲與頁面加載時的行爲完全一樣。

+0

我沒有真正考慮過將代碼放在其他地方,只是表明我在處理jQuery方面相當新穎。 – 2012-02-14 16:59:28

+0

但問題是我檢查一個元素是否在class列表中選擇了.selected。 (!$(this).hasClass('selected'))在我使用的地方,似乎不是正確的方法。 – 2012-02-14 17:10:19

相關問題