2016-11-28 37 views
0

如何簡化jQuery代碼。 如果我有幾個不同的塊的1頁。 我需要多次複製此代碼以使用不同的元素? 如何爲多個塊編寫1個代碼?如何簡化jQuery代碼,插件,滾動到塊

$('.go_to').click(function(){ 
     var scroll_el = $(this).attr('href'); 
      if ($(scroll_el).length != 0) { 
      $('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500); 
      } 
      return false; 
     }); 

    <a class="go_to" href="#elm">button</a> или <a class="go_to" href=".elm">block-scroll</a> 

$('.go_to-1').click(function(){ 
     var scroll_el = $(this).attr('href'); 
      if ($(scroll_el).length != 0) { 
      $('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500); 
      } 
      return false; 
     }); 

    <a class="go_to-1" href="#elm">button</a> или <a class="go_to-1" href=".elm">block-scroll</a> 

$('.go_to-2').click(function(){ 
     var scroll_el = $(this).attr('href'); 
      if ($(scroll_el).length != 0) { 
      $('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500); 
      } 
      return false; 
     }); 

    <a class="go_to-2" href="#elm">button</a> или <a class="go_to-2" href=".elm">block-scroll</a> 

回答

0

鑑於你例如,最簡單的方法是用逗號分隔的列表來選擇使用jQuery多個元素,和所有的人都在一次定義單擊處理:

$('.go_to, .go_to-1, .go_to-2').click(function(){ 
     //on click code 
    }); 

我假設你需要不同的班級,但如果不是,你可以給他們所有的班級(例如class="go_to")和使用

$('.go_to').click(function(){ 
     //on click code 
    });