2015-10-22 86 views
0

所以我有一个问题,在我的jQuery代码中,当下拉切换有数据切换='悬停'应该显示子菜单时,如果这个切换有数据切换='下拉“应该只在点击时显示子菜单。 该代码似乎工作,但当窗口被调整大小,属性被改变从HOVER到DROPDOWN(另一种方式似乎工作得很好)悬浮功能仍然执行无论如何。jQuery悬停功能在if语句中

下面的代码

function main() { 
    if (($('a.dropdown-toggle').attr('data-toggle'))=='hover') { 
     $('.dropdown').hover(function() { 
      $('ul.dropdown-menu', this).stop(true, true).slideDown(100); 
      $(this).addClass('open'); 
      }, function() { 
      $('ul.dropdown-menu', this).stop(true, true).slideUp(100); 
      $(this).removeClass('open'); 
      }); 
     } 
     } 
     $(document).ready(main); 
     $(window).resize(main); 

和属性changement功能

function clickEvent() { 
    if(viewport().width <= 991) { 
     $('a.dropdown-toggle').attr('data-toggle','dropdown'); 
    } else { 
     $('a.dropdown-toggle').attr('data-toggle','hover'); 
    } 
} 
$(document).ready(clickEvent); 
$(window).resize(clickEvent); 
+1

你已经设置了一些东西,以便你从“resize”事件调用'main()' - 每次调用它时,都会通过'.hover()'添加新的事件处理函数。那些jQuery事件处理程序API永远不会*替换先前的处理程序,它们总是在旧的处理程序之上添加新的处理程序,即使它们完全相同。 – Pointy

回答

1

尝试写事件处理程序的内部阻塞情况,

function main() { 
    $('.dropdown').hover(function() { 
     if ($('a.dropdown-toggle').data('toggle')!=='hover') { return; } 
     $('ul.dropdown-menu', this).stop(true, true).slideDown(100); 
     $(this).addClass('open'); 
     }, function() { 
     if ($('a.dropdown-toggle').data('toggle')!=='hover') { return; } 
     $('ul.dropdown-menu', this).stop(true, true).slideUp(100); 
     $(this).removeClass('open'); 
    }); 
} 

或更好的做一些调整在事件绑定中,

//remove the if statement inside of main function and do the below. 

function clickEvent() { 
    if(viewport().width <= 991) { 
     $('.dropdown').unbind('mouseenter mouseleave') 
    } else { 
     main(); 
    } 
} 
+0

你应该详细说明为什么OP应该这样做 – Adjit

0

或者,您可以对选择器进行更具体的描述,并彻底废除if声明。

尝试使用以下选择:

a.dropdown-toggle[data-toggle="hover"] 

$(document).on({ 
    mouseenter: function() { 
     //This function will execute when the dropdown-toggle is set to Hover 
     //and the mouse is hovering over the element 
     //some code like $(this).slideDown(100) 
    }, 
    mouseleave: function() { 
     //And this function will run after the the mouse leaves the selector element 
    } 
}, 'a.dropdown-toggle[data-toggle="hover"]'); 

而且,我不知道你想与你的大小调整和准备功能来完成的。但你不应该需要它们。