我是javascript的新手,我正在尝试编写一个垂直菜单。我让它在这一点上工作,这样当你点击一个列表项时,它就会改变div的内容。事情是这样的,我知道我写的javascript根本没有经过优化。
例如,如果我想向列表中添加另一项,则需要在现有脚本中添加大量代码。如果有人能给我一些指导,让我使用某种case/switch或if/else框架,用更少的代码做同样的事情,那就太好了。我尝试了几种不同的方法,但它们都没有像我想要的那样工作。
这是我现在正在做的一部分。divs #2-5在加载时是隐藏的,每个列表项都有一个点击功能,可以单独切换其他div的隐藏或显示。
$(document).ready(function(){
$('#feature2').hide();
$('#feature3').hide();
$('#feature4').hide();
$('#feature5').hide();
$('.feature1').click(function(){
$('#feature2').hide();
$('#feature3').hide();
$('#feature4').hide();
$('#feature5').hide();
$('#feature1').show();
});
$('.feature2').click(function(){
$('#feature1').hide();
$('#feature3').hide();
$('#feature4').hide();
$('#feature5').hide();
$('#feature2').show();
});
etc.下面是我正在尝试优化的代码的jsFiddle:http://jsfiddle.net/7PTUu/10/
谢谢!
发布于 2013-06-14 01:53:39
给你的每个link元素以及你想要隐藏/显示的div一个通用的CSS类(例如,"feature-link","feature")。然后将每个链接的href属性设置为它应该显示或隐藏的元素的ID。通过这种方式,您可以使用一个简单的处理程序完成所有这些操作。
示例HTML:
<!-- in your vertical menu -->
<a class="feature-link" href="#feature1">Feature 1</a>
<a class="feature-link" href="#feature2">Feature 2</a>
<!-- the features you want to show/hide -->
<div class="feature" id="feature1">...</div>
<div class="feature" id="feature2">...</div>示例JavaScript:
// Same logic applies to all links.
$(".feature-link").click(function() {
// Get the feature we want to show.
var target = $(this).attr("href");
// Hide all other feature elements
$(".feature").hide();
// Show just the one div.
$(target).show();
// This is personal preference; I put this here to prevent the ID
// from being appended to the URL in the browser's address bar.
return false;
});和here's a jsFiddle一起玩。
发布于 2013-06-14 01:50:55
最快的解决方案(但不是最优的):
$(document).ready(function() {
function hideDivs() {
$('#feature1, #feature2, #feature3, #feature4, #feature5').hide();
}
hideDivs();
$('.feature1').click(function(){
hideDivs();
$('#feature1').show();
});
$('.feature2').click(function(){
hideDivs();
$('#feature2').show();
});
...https://stackoverflow.com/questions/17093678
复制相似问题