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

标签 javascript jquery

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 个处理程序的 hover 方法(一个用于 mouseenter ,一个用于 mouseleave 事件)与 混淆了>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");

关于javascript - 为什么 .on() 方法不执行第一个处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29266604/

相关文章:

javascript - 语法错误 : Invalid character '\u8203'

javascript - 从对象javascript获取键

javascript - window.location.href 在 .html 后带有 # hash

javascript - DataTables:移位多选不起作用

javascript - VS代码: Add snippets to semantic completions?

javascript - 为什么javascript在使用替换时只替换第一个实例?

jquery - 为什么这段 JavaScript 代码没有禁用该按钮?

javascript - AJAX 响应后重新选择选项值

javascript - Webpack:提取文本插件和代码分割

javascript - 尝试将数字与符号匹配