0
我創建了一個使用引導CSS的HTML頁面。我有一個實際上是鏈接列表的邊欄列表。如何使用javascript點擊鏈接來有效地替換div內容?
<a href="#ut" class="list-group-item" id="utID">Update table</a>
我在HTML中有很多部分,默認情況下通過應用下面的CSS來隱藏。
<section id="ut" style="display:none;">
我想更改內容,當我點擊邊欄中的鏈接。我在這裏使用的是JavaScript,它將點擊鏈接的部分的CSS顯示設置爲阻止。爲了便於操作,我從鏈接的ID中刪除「ID」部分以獲得部分的ID 例如:link = utID,section = ut
以下給出了我用過的JavaScript。有沒有更好的優化方法來做到這一點?
// On clicking any of the side bar links
$('.list-group-item')
.click(function(event){
// Preventing the default action which may mess up the view
event.preventDefault();
// Getting all the anchor ids
var $a1 = document.getElementById("unfID");
var $a2 = document.getElementById("uiID");
var $a3 = document.getElementById("utID");
// Getting all the section ids
var $d1 = document.getElementById("unf");
var $d2 = document.getElementById("ui");
var $d3 = document.getElementById("ut");
// Store the id of the clicked link
var $clickedLink = $(this).attr('id');
// Storing the id of the corresponding Div by slicing of "ID" from the link's last part
var $clickedLinkDiv = $clickedLink.substring(0,$clickedLink.length-2);
// Setting the selected link active
SetLinkActive(document.getElementById($clickedLink))
// Setting the corresponding section visible
SectionVisibility(document.getElementById($clickedLinkDiv));
// Method to set the visibility of the section
function SectionVisibility(div){
// first hides al section
$d1.style.display = "none";
$d2.style.display = "none";
$d3.style.display = "none";
// then displays only the selected section
div.style.display = "block";
}
// Method to set the visibility of the section
function SetLinkActive(div){
// first deselect all links
$a1.className = "list-group-item";
$a2.className = "list-group-item";
$a3.className = "list-group-item";
// then applies selection to only the selected link
div.className = "list-group-item active";
}
});
哇,這太酷了。大幅減少行數!謝了哥們! – Gautam