javascript - jquery 鼠标事件的多种函数

标签 javascript jquery mouseevent

我正在开发一个 jQuery 插件。为了分离我的逻辑,我做了这样的事情:

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

然后在上面我再次执行此操作,但使用其他函数体

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

jQuery 如何处理这个问题?鼠标事件函数的第二个声明会覆盖第一个吗?有时我看到这两种方法都有效,但有时却无效。

最佳答案

Will 2nd declaration of mouse events function override the first one ?

没有。

How does jQuery deal with this ?

它按照事件处理程序附加的顺序执行它们。来自 the documentation (页面下方约 40%):

Event handlers bound to an element are called in the same order that they were bound.

例如,如果您有:

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

...然后点击 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). 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"); });

然后你点击div,你会得到

one
two
three

...在控制台中。

关于javascript - jquery 鼠标事件的多种函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25868179/

相关文章:

javascript - IE8 : element:first-child deosn't work (selects parent of what I actually want)

javascript - 从映射器(MapReduce)访问mongodb的对象

javascript - JS 使用类和超时创建闪烁?

jquery - 将父级的悬停应用于 jquery ui 自动完成子级

QT全局鼠标监听器

javascript - .on ('mouseenter' ...未检测到附加元素 (jQuery)

javascript - JS点钞机

javascript - 创建一个 chrome 扩展,它在页面上突出显示文本并将其插入 popup.html 中的文本区域

javascript - 认识 body 的宽度和高度

jQuery:嵌套多重选择器意外行为