我创建了一个使用bootstrap CSS的HTML页面。我有一个侧边栏列表,实际上是一个链接列表。
<a href="#ut" class="list-group-item" id="utID">Update table</a>
我在HTML中有很多部分,默认情况下会隐藏它们,如下所示。
<section id="ut" style="display:none;">
当我点击侧边栏中的链接时,我想更改内容。我在这里使用的是JavaScript,它将被点击链接的部分的CSS显示设置为阻止。为了便于操作,我删除了&#34; ID&#34;部分来自链接的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";
}
});
答案 0 :(得分:0)
使用jquery更容易!
<强> HTML 强>
<a href="#" class="list-group-item" id="unf">Update UNF</a>
<a href="#" class="list-group-item" id="ui">Update UI</a>
<a href="#" class="list-group-item" id="ut">Update UT</a>
<section class="unf" style="display:none;">
UNF SECTION
</section>
<section class="ut" style="display:none;">
UI SECTION
</section>
<section class="ui" style="display:none;">
UT SECTION
</section>
<强> 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();
$('a.list-group-item').removeClass('active');
$(this).addClass('active');
$('section').css('display', 'none');
$('section.' + $(this).attr('id')).css('display', '');
});