スタック オーバーフローへようこそ!
まず、jQueryを使用して JavaScript を支援することをお勧めします。jQuery (および Zepto、MooTools、Dojo などの他の同様のフレームワーク) は、クロスブラウザーの不一致など、JavaScript のいくつかの欠点を克服し、作業を大幅に容易にします。<head>
プロジェクトに jQuery を含めるには、ページのタグに次を追加するだけです。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
jQuery にアクセスできるようになったので、タグonclick
に追加したすべての属性を削除できます。<a>
タグの使用は、onclick
DOM レベル 1 標準が (ほぼ) 合意される前の Web 開発の初期にさかのぼるため、お勧めできません。代わりに、「クリック」イベントにバインドすることをお勧めします。これにより、HTML と JavaScript を分離し、JavaScript の読み取りとデバッグが容易になります。
jQuery を使用すると、ハンドラー (関数) をクリック イベントに簡単にバインドできます。次のon
構文を使用するだけです。
// #id is the 'id' attribute of the element you want to add a click handler to.
$('#id').on('click', function () { alert("Clicked!"); });
show
jQuery は、およびを介してページ上の要素をすばやく簡単に表示および非表示にする方法も提供しますhide
。
// Again, #id is the id attribute of the element you want to show/hide.
$('#id').show(); // Make a hidden element visible.
$('#id').hide(); // Hide a visible element.
ここで注意すべき唯一のことは、jQuery を使用して要素を「非表示」にすると、実際にdisplay
は要素の CSS 属性が設定されることです。visibility
上記のコードでは、属性を切り替えて要素を非表示にしていました。
答えの最後の部分は、現在表示されている要素をどのように処理するかにあります。これは、表示されている要素を追跡する新しい変数を追加することで実現できます。これは、以下の変更したコードで確認できます。
<html>
<head>
<style>
span.socialApp {
/* use display: none instead of visibilty: hidden */
display: none;
position:absolute;
top:20px;
left: 0;
background-color:#e9e9e9;
}
</style>
<!-- include jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Script for toggle apps -->
<script>
// Create an Array of all the app names.
var apps = [ 'app1', 'app2', 'app3' ];
// Variable which keeps track of which app is currently visible
var visibleAppName = null;
function onLinkClicked(event) {
// Get the id of the link that was clicked.
var linkName = event.target.id;
// Strip off the '-link' from the end of the linkName
var dashIndex = linkName.indexOf('-link');
var appName = linkName.substr(0, dashIndex);
// Call show app with the correct appName.
showApp(appName);
}
function showApp(appNameToShow) {
// Hide the currently visible app (if there is one!)
if (visibleAppName !== null) {
$('#' + visibleAppName).hide();
}
// And show the one passed
$('#' + appNameToShow).show();
// Update the visibleApp property.
visibleAppName = appNameToShow;
}
// $(document).ready waits for the page to finish rendering
$(document).ready(function () {
// Walk through the Array of Apps and add a click handler to
// it's respective link.
apps.forEach(function(name) {
$('#' + name + '-link').on('click', onLinkClicked);
});
});
</script>
</head>
<body>
<aside class="apps">
<a href="#" id="app1-link">link1</a>
<span class="socialApp" id="app1">stuff goes here1</span>
<a href="#" id="app2-link">link2</a>
<span class="socialApp" id="app2">stuff goes here2</span>
<a href="#" id="app3-link">link2</a>
<span class="socialApp" id="app3">stuff goes here3</span>
</aside>
</body>
</html>
JavaScript 開発について詳しく知りたい場合は、オブジェクト指向 JavaScriptを読むことをお勧めします。これは、言語とその癖の優れた紹介を提供します。