2017-02-03 134 views
-1

我有一系列div,我想根据用户可以点击的链接显示和隐藏。有没有一种方法来重构这些功能,以减少重复?重构jQuery显示/隐藏

可能使用切换?

$('#section1').hide(); 
$('#section2').hide(); 
$('#section3').hide(); 
$('#section4').hide(); 

$('#section1-link').click(function() { 
    $('#section1').show(); 
    $('#section2').hide(); 
    $('#section3').hide(); 
    $('#section4').hide(); 
}); 
$('#section2-link').click(function() { 
    $('#section1').hide(); 
    $('#section2').show(); 
    $('#section3').hide(); 
    $('#section4').hide(); 
}); 
$('#section3-link').click(function() { 
    $('#section1').hide(); 
    $('#section2').hide(); 
    $('#section3').show(); 
    $('#section4').hide(); 
}); 
$('#section4-link').click(function() { 
    $('#section1').hide(); 
    $('#section2').hide(); 
    $('#section3').hide(); 
    $('#section4').show(); 
}); 
+4

是,用普通的类来代替。 –

+0

是的,只需调用.click来绑定一次事件。没有必要这样做4次。 –

+0

@KevinB但每个人的代码是不同的。 – Barmar

回答

0

Working fiddle

我建议在data-*的帮助下使用常见的类,请查看下面的示例。

希望这会有所帮助。

$('.section-link').on('click', function(){ 
 
    var section_id = '#'+ $(this).data('section'); 
 

 
    $('.section').hide(); //Hide all sections 
 
    $(section_id).show(); //Show the related one 
 
})
div:not(#section1){ 
 
    display:none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a href='#' class='section-link' data-section='section1'>Link 1</a> 
 
<a href='#' class='section-link' data-section='section2'>Link 2</a> 
 
<a href='#' class='section-link' data-section='section3'>Link 3</a> 
 
<a href='#' class='section-link' data-section='section4'>Link 4</a> 
 

 
<div class='section' id='section1'>Section 1</div> 
 
<div class='section' id='section2'>Section 2</div> 
 
<div class='section' id='section3'>Section 3</div> 
 
<div class='section' id='section4'>Section 4</div>