2017-02-03 129 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>