2011-04-23 95 views
0
<script> 
$(document).ready(function() { 
// for some reason the button hide has to be at the top 
$("button").click(function() { 
    $(".holcomb, .lunden, .maggie, .rosewood").hide("slow"); 
    $("button").hide("fast"); 
}); 
// examples show hide 
$(document).ready(function() { 
    $("a#holcomb").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("fast"); 
     $("button").hide("fast") 
     $(".holcomb").slideDown(1500); 
     $("button#holcomb").show("fast") 
    }); 
}); 
$(document).ready(function() { 
    $("a#lunden").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("fast"); 
     $("button").hide("fast") 
     $(".lunden").slideDown(1500); 
     $("button#lunden").show("fast") 
    }); 
}); 
$(document).ready(function() { 
    $("a#maggie").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("fast"); 
     $("button").hide("fast") 
     $(".maggie").slideDown(1500); 
     $("button#maggie").show("fast") 
    }); 
}); 
$(document).ready(function() { 
    $("a#rosewood").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("fast"); 
     $("button").hide("fast") 
     $(".rosewood").slideDown(1500); 
     $("button#rosewood").show("fast") 
    }); 
}); 
</script> 

我只是需要帮助简化这个脚本。如何简化这个jQuery代码?

发生的一切是,我有一些链接,当你点击他们的div(与类)显示。然后一个按钮也会在链接旁边弹出,然后当你点击它时关闭(显然),或者当你点击另一个链接时,它会关闭当前打开的div并打开另一个div。类

+0

你是否在多个元素上使用相同的'id'?这不是有效的HTML,你知道 – 2011-04-23 02:00:06

+0

不,我为每个按钮使用不同的id元素,其他一切都在使用类。 – user645607 2011-04-23 02:01:09

回答

0

添加类的所有元素你想拥有这显示/隐藏的东西上工作那么你可以这样做:

var $allElements = $(".showHide"); 


$allElements.click(function() { 
    $allElements.hide("fast"); 
    $(this).slideDown(1500); 
    /* you'd have to add some logic here for the matching button... 
     ...perhaps give it an ID matching the link with a suffix of '-button' 
     or something */ 
}); 
2

更出色的应用将使这个代码更简单,但你有什么工作......

$(document).ready(function(){ 
    $("button").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("slow"); 
     $("button").hide("fast"); 
    }); 

    $("a#holcomb, a#lunden, a#maggie, a#rosewood").click(function() { 
     $(".holcomb, .lunden, .maggie, .rosewood").hide("fast"); 
     $("button").hide("fast"); 
     $("."+this.id).slideDown(1500); 
     $("button#"+this.id).show("fast") 
    }); 
}); 
+0

那么更好的课程是什么?并感谢你 – user645607 2011-04-23 01:49:25