2015-03-13 30 views
0

我已經通過StackOverflow搜索了我認爲是一個基本問題,但找不到任何相關的線程。主要是因爲我覺得我正在尋找錯誤的關鍵字。將多個相似的功能組合成一個

我想知道如何總結下幾行代碼儘可能少。當你點擊'link-#'時,它會從隱藏的div'more-#'中加載內容(其中#中的more可以是任何數字,但與link-#中的數字相同)。有這樣的:

jQuery("#link-1").click(function(){ 
    jQuery('#more').hide().html($('#more-1').html()).fadeIn(400) 
}); 
jQuery("#link-2").click(function(){ 
    jQuery('#more').hide().html($('#more-2').html()).fadeIn(400) 
}); 
jQuery("#link-3").click(function(){ 
    jQuery('#more').hide().html($('#more-3').html()).fadeIn(400) 
}); 

我認爲它應該像下面,但顯然這不是正確的做法。

jQuery("#link" + NUMBER).click(function(){ 
    jQuery('#more').hide().html($('#more-' + this.NUMBER).html()).fadeIn(400) 
}); 

我打賭你們知道如何處理這個問題!感謝您的幫助。

最好的問候,

托馬斯

回答

1

給他們所有相同的類名,然後添加屬性 「數據-NUM」,然後:

jQuery(".className").click(function() { 
    var $this = $(this); 
    var html = jQuery('#more' + $this.attr('data-num')).html(); 
    jQuery('#more').hide().html(html); 
}); 

示例HTML:

<a class='className' data-num='1'>Link</a> 
<div id='more1'></div> 
<div id='more'></div> 
2

一個更好的方法是將這些項目分組給他們相同的類別,並使用一個data-*屬性來標識相關聯的元件:

jQuery(function() { 
 
    jQuery(".show-more").click(function() { 
 
    var target = $(this).data('target'); 
 
    jQuery('#more').hide().html($(target).html()).fadeIn(400); 
 
    }); 
 
});
#moreItems { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<a href="#" class="show-more" data-target="#more-1">Show More 1</a> 
 
<a href="#" class="show-more" data-target="#more-2">Show More 2</a> 
 
<a href="#" class="show-more" data-target="#more-3">Show More 3</a> 
 
<div id="more"></div> 
 
<div id="moreItems"> 
 
    <div id="more-1">Here are the details 1</div> 
 
    <div id="more-2">Here are the details 2</div> 
 
    <div id="more-3">Here are the details 3</div> 
 
</div>

+2

也許是更好的方法是把一個選擇器在像'DATA- *'屬性:''Show More 1,自舉(2 OU 3,不記得)在一些組件中使用它 – 2015-03-13 19:02:14

+0

@Sanção是的,我同意。謝謝! – JLRishe 2015-03-13 19:05:27