2011-04-23 94 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