,歡迎堆棧溢出!
首先,我將建議您使用jQuery幫助您使用JavaScript。 jQuery(以及Zepto,MooTools和Dojo等其他類似框架)對JavaScript中的一些裂縫如cross browser inconsistencies和make things a lot easier進行了修改。包括jQuery的在你的項目,你只需要添加到網頁的<head>
標籤以下內容:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
jQuery的現在,你就可以訪問你可以刪除所有onclick
的屬性,您添加到您的<a>
標籤。使用onclick
標籤是不鼓勵的,因爲它可以追溯到web開發的早期階段,而DOM(第1層)標準已經(幾乎)同意。相反,它建議你綁定到'點擊'事件 - 這將有助於保持你的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!"); });
的jQuery還提供了一個快速簡便的方法來顯示和隱藏要素通過show
和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的元素,它實際上將T的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的開發則可能我建議閱讀Object Orientation JavaScript它提供了一個很好的介紹語言和一些它的怪癖。
歡迎來到SO!偉大的第一個問題,但你會發現更多的人想要回答,如果你確保正確縮進你的代碼,以便更易於閱讀。 – Jivings