2010-06-01 64 views
1

我有一個關於如何使用jQuery標籤(點擊鏈接按鈕來顯示/隱藏某些div)的快速問題。Javascript隱藏/顯示使用JQuery的標籤

HTML鏈接:

<table class='layout tabs'> 
<tr> 
    <td><a href="#site">Site</a></td> 
    <td><a href="#siteno">Number</a></td> 
</tr> 
<tr> 
    <td><a href="#student">Student</a></td> 

    <td><a href="#school">School</a></td> 
</tr> 
</table> 
</div> 

的div需要顯示/隱藏:在DIV ID鏈接的href匹配

<div id="site"> 
    <table class='explore'> 
    <thead class='ui-widget-header'> 
     <tr> 
     <th class=' sortable'> 
      Site 
     </th> 

     <th class=' sortable'> 
      Number 
     </th> 
     </tr> 
     </thead> 
     </table> 
</div> 

回答

2
$("table.tabs a").click(function() { 
    var id = $(this).attr("href"); 
    var div = $(id); 
    div.toggle(); 
}); 

這將讓你正是你「問。但是,我懷疑你也想在顯示一個div時隱藏所有其他的div。真正?

好的,現在你已經回覆說它是真的,這是你的新代碼。 你也應該在你的所有DIV中添加一個類(在我的代碼 - 「tab-div」中),以便讓它們輕鬆地在一起進行選擇。

$("table.tabs a").click(function() { 
    var id = $(this).attr("href"); 

    // Hide all the tab divs 
    $(".tab-div").hide(); 

    // Then show the one that's been clicked 
    $(id).show(); 
}); 
+0

是的。謝謝 – JohnMerlino 2010-06-01 18:02:16

+0

好吧,如果你這樣做,你應該在你原來的問題中問這個問題,不是嗎?我編輯了答案。 – 2010-06-01 18:57:43

+0

只是fyi。在你的第一個例子中,代碼「if(div.is(」:visible「))div.hide(); else div.show();」可以修改爲div.toggle(); – corymathews 2010-06-01 19:05:19