2011-05-23 31 views
0

在我的頁面上,我放置了兩個div:nav和內容。 在「nav」裏面,我有10個鏈接。每個人都稱爲「link1」,「link2」,.... 在「內容」裏面,我有10個divs。每個人都叫ilke「divarea1」,「divarea2」,.... 當我點擊鏈接,新的內容將淡入淡出。 我jQuery代碼是這樣的:jquery fadein問題

$("#link1").click(function(){ 
    $("#divarea0,#divarea2,#divarea3,#divarea4,#divarea5,#divarea6,#divarea7,#divarea8,#divarea9,#divarea10").hide(); 
    $("#divarea1").fadeIn(3000); 
}); 
$("#link2").click(function(){ 
    $("#divarea0,#divarea1,#divarea3,#divarea4,#divarea5,#divarea6,#divarea7,#divarea8,#divarea9,#divarea10").hide(); 
    $("#divarea2").fadeIn("fast"); 
}); 

這種方式工作。但我知道這是一個愚蠢的方式。有人可以告訴我如何以簡單的方式做到這一點? thx

+0

它會有幫助,如果你把你的snipet html也在這裏 – Adelave 2011-05-23 14:27:57

回答

0
$('#nav a').click(function(){ 
var idlink = $(this).attr('id').substr(4,2); 
$('#contents div').hide(); 
$('#divarea"+idlink).fadeIn(); 

}

首先,你聽在#nav div中的所有鏈接上點擊事件。然後,單擊時,您將獲得id屬性,並將不需要的所有字符減去僅獲取鏈接的「索引」。 您可以隱藏#contents中的所有div,並使用之前有兩行的索引淡入所有#divarea。

我不確定這是最好的方式,但它更好,它應該工作! :)

+0

我喜歡這種方式。太精彩了!非常感謝你! – nich 2011-05-24 13:24:22

2

我看到我們可以做的一些事情。我們可以使用jQuery的.data()功能,並指定鏈接的兩個「動態」部分:要顯示的內容區域和要顯示的速度。從那裏,我們綁定並從每個鏈接拉這些值。例如:

<div id="nav"> 
    <a href="#" data-area="1" data-speed="3000">Link 1</a> 
    <a href="#" data-area="2" data-speed="fast">Link 2</a> 
    ... 
</div> 

$(function(){ 
    // locate and iterate over all the links in the nav container 
    $('#nav a').each(function(i,e){ 
    // use the "data-area" to determine the content to display 
    var area = $(e).data('area'); 
    // use the "data-speed" to determine how fast the content should be shown/hidden 
    var speed = $(e).data('speed'); 

    // bind the click event 
    $(e).click(function(e){ 
     // use a selector to find divs that match the prefix "divarea" 
     $('div[id^=divarea]').hide(); 

     // now show the correct content using the two data fields we got earlier 
     $('#divarea' + area).fadeIn(speed); 
    }); 
    }); 
}); 

Demo

-

如果你想保持鏈路ID,這裏是一個替代方法。錨還必須有data-speed,但可以保留的ID linkN(其中N是一個數字):

$(function(){ 
    $('#nav a').each(function(i,e){ 
     var area = $(e).attr('id').match(/(\d+)$/); 
     var speed = $(e).data('speed'); 

     $(e).click(function(e){ 
      $('div[id^=divarea]').hide(); 
      $('#divarea' + area).fadeIn(speed); 
     }); 
    }); 
}); 

Demo

+0

非常感謝。但是當我嘗試這些代碼時,它不起作用。我不知道爲什麼。 – nich 2011-05-24 13:25:05

0

我建議像這樣: 添加類「鏈接」或任何你想要的每個鏈接和一個名爲「link_5」,這是下劃線與你要顯示的div關係後的數字。所以你還必須在id爲「nav_5」的「contents」包裝器中添加一個「nav」類,這個編號對應於appropritate鏈接。然後:

$(".link").click(function(){ 
    var id = $(this).split('_')[1]; //You get the id value after the underscore 
    $('.nav').hide(); // You hide all div with the class "nav" 
    $('#nav_'+id).fadeIn(3000); // You display the div with the id "nav_[id]" 
}); 

只是讓你瞭解完全地,該。鏈路類是你一種方式來獲得只有一個jQuery的請求的所有鏈接。如果你點擊鏈接,你可以將id值分開以獲得正確的內容div的id。這是任何瀏覽器的有效方法,如果您想使用W3C驗證您的網站,則不會收到任何「DOM」錯誤。希望它有幫助

+0

$('#contents div')。hide()(previous answer)實際上比向每個div添加類要好。 – Bene 2011-05-23 15:46:39