2015-07-03 43 views
1

這兩個代碼塊基本上是相同的只是不同的元素是如何將我去到一個可重複使用的腳本將它們合併jQuery的單擊事件合併成一個單一DRY代碼塊

$('.menu-button').on('click', function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    $('#sidebar').toggleClass('sidebar-open'); 
    $('#cart').removeClass('cart-open'); 

    $(document).one('click', function closeMenu (e){ 
     //console.log("DF"); 
     if($('#sidebar').has(e.target).length === 0){ 
      console.log("DF"); 
      $('#sidebar').removeClass('sidebar-open'); 
     } else { 
      $(document).one('click', closeMenu); 
     } 
    }); 
}); 

$('.cart-button').on('click', function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    $('#sidebar').removeClass('sidebar-open'); 
    $('#cart').toggleClass('cart-open'); 


    $(document).one('click', function closeMenu (e){ 
     //console.log("DF"); 
     if($('#cart').has(e.target).length === 0){ 
      $('#cart').removeClass('cart-open'); 
     } else { 
      $(document).one('click', closeMenu); 
     } 
    }); 
}); 

回答

0

嘗試爲click事件定義單個處理程序processMenu;設置選擇器elem使用event.target.className

var processMenu = function processMenu(e) { 
     var elem = $(e.target.className === "menu-button" ? "#sidebar" : "#cart"); 
     e.preventDefault(); 
     e.stopPropagation(); 
     $("#sidebar").toggleClass("sidebar-open"); 
     $("#cart").removeClass("cart-open"); 

     $(document).one("click", function closeMenu (evt){ 
     //console.log("DF"); 
     if(elem.has(evt.target).length === 0){ 
      console.log("DF"); 
      elem.removeClass("sidebar-open"); 
     } else { 
      $(document).one("click", closeMenu); 
     } 
     }); 
    }; 

    $(".menu-button, .cart-button").on("click", processMenu); 
0

使用逗號:

$('.menu-button, .cart-button').on('click', function(e) { 
    var param = $(this).is('.menu-button') ? "sidebar" : "cart"; 
    e.preventDefault(); 
    e.stopPropagation(); 
    $('.cart-open').removeClass('cart-open'); 
    $('.sidebar-open').removeClass('sidebar-open'); 
    $('#' + param).toggleClass(param + '-open'); 

    $(document).one('click', function closeMenu (e){ 
     //console.log("DF"); 
     if($("#" + param).has(e.target).length === 0){ 
      console.log("DF"); 
      $("#" + param).removeClass(param + '-open'); 
     } else { 
      $(document).one('click', closeMenu); 
     } 
    }); 
}); 

編輯:此外,使用速記if語句來查明它的側邊欄或點擊的購物車,在休息中使用它。

相關問題