2012-02-14 64 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

相关问题