mouseenter和mouseleave事件处理触发多次

时间:2016-10-26 15:58:51

标签: javascript jquery

我有一段javascript代码,当我将鼠标悬停在ul上时,它会在菜单栏上显示下拉列表。我的菜单栏可以在点击时关闭,再次点击可以再次打开。我的代码如下:

$('li.dropdown').on({
  mouseenter: function() {
    //stuff to do on mouse enter
    console.log('hi')
    $(this.children[0]).trigger('click'); //upon hover, displays the toggle menu
  },
  mouseleave: function() {
    //stuff to do on mouse leave
    console.log('bye')
    $(this.children[0]).trigger('click'); //closes the menu when not hover
    $(document.activeElement).blur(); //takes the focus away from the element so the blue background color wont stay
  }
})

所以当我重新加载页面时,我点击我的菜单栏打开并将鼠标悬停在下拉列表上,它运行正常。在我的控制台中,我得到'嗨'然后'再见'。但是,当我关闭菜单栏并再次打开它并将鼠标悬停在下拉列表上时,没有任何反应。下拉列表未显示。这是因为鼠标中心功能的点击是两次触发。我知道这是因为在我的控制台中,我看到'hi'x2,当我把鼠标移开时,我得到'bye'x3。当我继续重复这个过程而不刷新我的页面时,'hi'和'bye'递增1。所以它将是'hi'x3接下来是'hi'x4。因此,悬停仅适用于奇数次点击。

0 个答案:

没有答案