【发布时间】:2011-08-25 02:50:50
【问题描述】:
这里是 jQuery/javascript 的新手并寻求一些帮助。我正在编写一个带有简单导航菜单的网站。它是这样工作的。用户单击菜单中的链接,该链接被设置为“活动”颜色,并且相应的部分从隐藏设置为可见(当文档加载时,所有部分都设置为隐藏)。当用户单击另一个链接时,该链接设置为活动颜色,其他链接设置为默认颜色,任何可见部分都设置为隐藏,相关部分设置为可见。这工作得很好,但我使用了单个元素,它非常难看,有很多重复。我正在重写代码以使用 .classes 并使用更少的重复代码更加灵活。
我的问题是:如何告诉它要显示哪个部分?
用户点击a.linkfornavigation,颜色被设置,section.blah被设置为隐藏,section#thisiswhatyouwant被设置为可见。但是我如何告诉 a.linkfornavigation 它应该指向哪里呢?每个部分都有一个唯一的#id(我猜他们点击的链接也可以)但是我如何从点击的链接中获取相关链接部分的#id?
非常感谢任何帮助。
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/linkthinger-hybrid.css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/linkthinger-hybrid.js" type="text/javascript"></script>
</head>
<body>
<section id="links">
<a class="thinger" href="#">Thing One</a>
<a class="thinger" href="#">Thing Two</a>
<a class="thinger" href="#">Thing Three</a>
<a class="thinger" href="#">Thing Four</a>
<a class="thinger" href="#">Thing Five</a>
</section>
<section id="things">
<section id="thingone" class="thing">I am thing one.</section>
<section id="thingtwo" class="thing">I am thing two.</section>
<section id="thingthree" class="thing">I am thing three.</section>
<section id="thingfour" class="thing">I am thing four.</section>
<section id="thingfive" class="thing">I am thing five.</section>
</section>
</body>
javascript:
$(document).ready(function(){
// Hides .thing class as soon as the DOM is ready.
// $('section.thing').hide(0);
// Highlight selected link & set all others to default.
$('#links a').click(function(){
$(this).addClass('selected');
$(this).siblings().removeClass('selected');
});
// Shows one section and hides all others on clicking the noted link.
$('a.thinger').click(function() {
$('section.thing').hide(0);
$('#thingone').fadeIn('slow');
return false;
});
})
CSS:
a {
color: darkgreen;
}
.selected {
color: red;
}
section.thing {
background-color: blue;
}
【问题讨论】:
-
顺便说一句:jsfiddle.net 是一个很好的示例网站
-
您可以通过数组索引访问链接,就像您通过索引访问部分一样。
标签: javascript jquery