为什么 .on() 方法不执行第一个处理程序

Why doesn't .on() method execute the first handler?

本文关键字:执行 第一个 处理 程序 方法 on 为什么      更新时间:2023-09-26
var x;
userList.on( "mouseover", "li", function(e) {
    console.log('1');
    x = setTimeout( function() { 
        doThis();
    }, 700);
},function(){
    console.log('3');
    clearInterval(x);
});
userList.on( "mouseleave", "li", function(e) {
    showProfile.css('display', 'none');
});

现在,每当我将鼠标悬停在用户列表上时,它都会向我显示console.log('3')在这种情况下我做错了什么?

您似乎将接受 2 个处理程序(一个用于mouseenter,一个用于mouseleave事件(hover方法与 on 方法混淆了。您应该只将一个回调函数传递给 on 方法。在这种情况下,第一个函数用作可选的 data 参数,第二个函数用作处理程序:

.on( events [, selector ] [, data ], handler )

event对象的data属性引用传递的函数。您可以使用调用运算符调用该函数()

userList.on( "mouseover", "li", function(e) {
    console.log('1');
    x = setTimeout( function() { 
        doThis();
    }, 700);
},function(event) {
    event.data(); // calls the first function
    // ...
});

另请注意,mouseentermouseover是两个不同的事件。你应该听mouseover/mouseoutmouseenter/mouseleave

对于清除函数设置的超时setTimeout您应该使用 clearTimeoutclearInterval用于清除setInterval函数设置的间隔。

var x;
userList.on({
   mouseenter: function() {
       x = setTimeout( function() { 
          doThis();
       }, 700);
   },
   mouseleave: function() {
      clearTimeout(x);
      // showProfile.css('display', 'none');
      // ...
   }
}, "li");