【问题标题】:How to simplify this jQuery code?如何简化这个 jQuery 代码?
【发布时间】:2011-04-23 01:35:05
【问题描述】:
<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>

我只是需要帮助来简化这个脚本。

所有发生的事情是,我有一些链接,当您单击它们时,会显示一个 div(带有一个类)。然后链接旁边还会弹出一个按钮,然后当您单击它时(显然)或当您单击另一个链接时,它会关闭当前打开的 div 并打开另一个 div。

【问题讨论】:

  • 您是否在多个元素上使用相同的id?这不是有效的 HTML,你知道
  • 不,我为每个按钮使用不同的 id 元素,其他一切都在使用类。

标签: jquery button hide show simplify


【解决方案1】:

简单地更好地应用类将使这段代码更简单,但使用你所拥有的......

$(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")
   });
});

【讨论】:

    【解决方案2】:

    为所有你想让这个显示/隐藏的东西工作的元素添加一个类,然后你可以这样做:

    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 */
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 2021-01-09
      • 2011-01-29
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      相关资源
      最近更新 更多