2012-07-16 58 views
1

我已经创建了一个下拉菜单。这个菜单通过指向父div打开。我想隐藏,当用户离开两本div父股利或下拉菜单如何绑定两个html元素上的事件

$(function(){ 
$('.a').live('mouseenter',function(){ 
    $('#dropdown').stop(false, true).hide(); 

    var id = $(this).attr('id'); 
    $('#dropdown').css({ 
     position:'absolute', 
     top: $(this).offset().top + $(this).height() + 'px', 
     right: '115px', 
     left: $(this).offset().left + 'px', 
     zIndex:1000, 
     width:'100px' 
    }); 

    $('#dropdown').stop().slideDown(500); 

    if($('#dropdown').mouseleave() && $('#'+id).mouseleave()){ 
     $('#dropdown').slideUp(500); 
    } 
}); 
}); 

Live Demo

+4

你是否知道['.live()'已弃用](http://liveisdeprecated.com)?你应该使用'.on()'代替(或'.delegate()',如果你被困在1.7以下版本的jQuery中)。 – 2012-07-16 07:53:49

+0

在控制台上使用'on'错误是'未捕获TypeError:Object [object Object]没有'on' – 2012-07-16 07:59:53

+0

您使用的是哪个版本的jQuery? – 2012-07-16 08:00:39

回答

1

你必须添加鼠标离开事件,并检查下拉列表中,要尽量简短,尽量this

我希望这是你想要什么

2

您可以通过选择用逗号分隔条件将它们绑定到多个元素

$('.a, .this, .that, div, form').live(.... 
1

使用多个选择器作为@Dale建议或使用相同的类为这两个元素和使用

$(".commonClass").live(function(){ 

}); 

如果您想将相同的事件绑定到更多的元素,您只需将commonClass应用于它们,而不是添加新的选择器。

1

试试这个演示:http://jsfiddle.net/AQweU/http://jsfiddle.net/k986c/

事情很少;

  • 使用.on事件而不是直播。
  • 使用this.id而不是$(this).attr('id')
  • 不知道这情况if($('#dropdown').mouseleave() && $('#'+id).mouseleave()){见下面我做了什么

请注意,这个问题的演示代码中有JQ 1.7.2因此.on使用。

休息检出码:(希望这有助于casue):)

$(function(){ 
    $('.a,#dropdown').on('mouseenter',function(){ 
     $('#dropdown').stop(false, true).hide(); 

     var id = this.id; 
     $('#dropdown').css({ 
      position:'absolute', 
      top: $(this).offset().top + $(this).height() + 'px', 
      right: '115px', 
      left: $(this).offset().left + 'px', 
      zIndex:1000, 
      width:'100px' 
     }); 

     $('#dropdown').stop().slideDown(500); 

     $('#dropdown, #'+id).mouseleave(function(){ 
      $('#dropdown').slideUp(500); 

     }); 
    }); 
}); 
​ 
+0

通过使用'on'控制台上的错误是'Uncaught TypeError:Object [object Object] has'method'on'' – 2012-07-16 08:00:15

+0

http://jsfiddle.net/k986c/?试试这个@RanaMuhammadUsman我在chrome - alienware上似乎工作正常 – 2012-07-16 08:01:10

+0

'.on()'的这种用法并不等同于'.live()'。你需要像'$(document).on('mouseenter','a',function(){/ ** /})''。另外,如果他的jQuery比1.7早,'.on()'不起作用。 – nbrooks 2012-07-16 08:02:15