如何简化jQuery代码,插件,滚动到块



如何简化jQuery代码。 如果我有 1 个页面,其中包含几个不同的块。 我需要多次复制此代码才能使用不同的元素? 如何为多个块编写 1 个代码?

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

给定您的示例,最简单的方法是使用逗号分隔的列表使用 jquery 选择多个元素,并一次定义所有元素的单击处理程序:

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

我假设您需要不同的锚点类,但如果没有,您可以给它们所有相同的类(例如class="go_to")并使用

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

最新更新