,欢迎堆栈溢出!
首先,我将建议您使用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