简体   繁体   English

鼠标事件的多种功能jQuery

[英]Multiple functions for mouse events jquery

I'm working on a jQuery plugin. 我正在开发jQuery插件。 To separate my logic I do something like this: 为了分开我的逻辑,我做这样的事情:

$element.on({
    mouseenter: function(){
      //do something special
    }, mouseleave: function(){
      //do something else special
    }
});
//more stuffs

and then above this I do that again but with other function body 然后在此之上我再次使用其他功能主体执行此操作

$element.on({
    mouseenter: function(){
      //do something not special
    }, mouseleave: function(){
      //do something else not special
    }
});

How does jQuery deal with this ? jQuery如何处理呢? Will 2nd declaration of mouse events function override the first one ? 鼠标事件函数的第二个声明会否覆盖第一个? Sometimes I see both things works but sometimes not. 有时我看到两种方法都有效,但有时却不行。

Will 2nd declaration of mouse events function override the first one ? 鼠标事件函数的第二个声明会否覆盖第一个?

No. 没有。

How does jQuery deal with this ? jQuery如何处理呢?

It executes your event handlers in the order in which they were attached. 它按照它们附加的顺序执行事件处理程序。 From the documentation (about 40% down the page): 文档 (大约40%):

Event handlers bound to an element are called in the same order that they were bound. 绑定到元素的事件处理程序的调用顺序与其绑定的顺序相同。

So for instance, if you have: 因此,例如,如果您有:

var div = $("#someDiv");
div.on("click", function() { console.log("one"); });
div.on("click", function() { console.log("two"); });
div.on("click", function() { console.log("three"); });

...then clicking the div will give you ...然后单击div将给您

one
two
three

...in the console. ...在控制台中。

Note that it doesn't matter how you found the element to attach the handlers. 请注意,如何找到要附加处理程序的元素并不重要。 Let's say you have only one div on the page, it has the id "someDiv" , and it's the first child of body (just to make the selectors easy). 假设您在页面上只有一个div ,它的id "someDiv" ,并且它是body的第一个子"someDiv" (只是为了使选择器易于操作)。 If you have: 如果你有:

$("#someDiv").on("click", function() { console.log("one"); });
$(document.body).children().first().on("click", function() { console.log("two"); });
$("div").on("click", function() { console.log("three"); });

and you click the div, you'll get 然后单击div,您将获得

one
two
three

...in the console. ...在控制台中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM