简体   繁体   中英

How to simplify jQuery code , plugin, scroll to the block

How to simplify jQuery code. If I have 1 page with several different blocks. I need to duplicate this code multiple times to use different elements? How to write 1 code for multiple blocks ?

  $('.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>

Given your example, the simplest way is to select multiple elements with jquery using a comma separated list, and define the click handler all of them at once:

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

I am assuming you need different classes for the anchors, but if not, you could just give them all the same class (for example class="go_to" ) and use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM