jQuery 不能使用 .bind() 绑定悬停

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4111194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:41:54  来源:igfitidea点击:

cannot use .bind() to bind hover

jquery

提问by Sinan

I experimenting with jQuery. As I was trying I found out that I can't use hover event with .bind. And I don't know what is wrong.

我正在试验 jQuery。当我尝试时,我发现我不能在 .bind 中使用悬停事件。我不知道出了什么问题。

$(document).ready(function(){
 $('.some-class').bind({
  hover: function(e) {
  // Hover event handler
   alert("hover");
  },
  click: function(e) {
  // Click event handler
   alert("click");
  },
  blur: function(e) {
  // Blur event handler
  }
 });
});

What is surprising (at least to me) is that hover is not working. The others "click" and "blur" are working fine.

令人惊讶的(至少对我而言)是悬停不起作用。其他“点击”和“模糊”工作正常。

Also the following works without any problems.

以下工作也没有任何问题。

$(".some-class").hover(function(){
     // stuff
})

Maybe I can use the above code. But not knowing why is a big nuisance. So any ideas?

也许我可以使用上面的代码。但不知道为什么是一个大麻烦。那么有什么想法吗?

Thanks!

谢谢!

回答by Nick Craver

You need to use the mouseenterand mouseleaveevents (which .hover()uses) directly when binding with an object like this:

在与这样的对象绑定时,您需要直接使用mouseentermouseleave事件(.hover()使用):

$(document).ready(function(){
 $('.some-class').bind({
  mouseenter: function(e) {
  // Hover event handler
   alert("hover");
  },
  mouseleave: function(e) {
  // Hover event handler
   alert("hover");
  },
  click: function(e) {
  // Click event handler
   alert("click");
  },
  blur: function(e) {
  // Blur event handler
  }
 });
});

.hover()is defined specially herein the jQuery event code...it simply isn't supported like other events in places like .bind(), since it's not an event, it's just a function to help you bind the mouseenterand mouseleaveevents.

.hover()在 jQuery 事件代码中专门在这里定义了...它不像其他地方的事件那样受支持.bind(),因为它不是一个事件,它只是一个帮助您绑定mouseentermouseleave事件的函数。

回答by Jason McCreary

Not much of a why, but it is simply not in the spec. Check the doc - hover is not listed in the bindable events.

没有太多原因,但它根本不在规范中。检查文档 - 可绑定事件中未列出悬停。

http://api.jquery.com/bind/

http://api.jquery.com/bind/