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;">
サイドバーのリンクをクリックするとコンテンツを変更したいと考えています。私がここで使用したのは、クリックされたリンクのセクションのCSS表示をブロックするJavaScriptです。簡単な操作のために、リンクの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