2015-10-22 28 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"]'); 

而且,我不知道你想與你的大小調整和準備功能來完成的。但你不應該需要它們。