我创建了一个使用 bootstrap CSS 的 HTML 页面。我有一个侧边栏列表,它实际上是一个链接列表。
<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";
}
});
最佳答案
使用 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', '');
});
关于javascript - 如何在使用 javascript 单击链接时有效地替换 div 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42469792/