2014-02-10 83 views
0

我有點麻煩讓腳本工作。我不知道我哪裏錯了。任何幫助,將不勝感激請。它的學習正在進行中。JQuery slideToggle函數與單獨的關閉按鈕

我在我的頁面上設置了一個開關,除了當內容div打開時,我在打開的div內有一個關閉按鈕,點擊時需要關閉內容div。這是我的代碼:

<script type="text/javascript"> 
jQuery(document).ready(function() { 
    jQuery(".chairmanContent").hide(); 
    //toggle the componenet with class msg_body 
    jQuery(".chairmanReadmore").click(function() 
    { 
    jQuery(this).next(".chairmanContent").slideToggle(500); 
    }); 
}); 

jQuery(document).ready(function() { 
    jQuery(".chairmanContent").hide(); 
    //toggle the componenet with class msg_body 
    jQuery(".chairmanClose").click(function() 
    { 
    jQuery(this).next(".chairmanContent").slideUp(500); 
    }); 
}); 
</script> 

我不確定是否使用slideUp是解決此問題的正確方法。

在此先感謝。乾杯。

回答

0

所以不是.next()使用.closest()

改變這一點:

jQuery(this).next(".chairmanContent").slideUp(500); 

這樣:

jQuery(this).closest(".chairmanContent").slideUp(500); 
//-----------^-----^---------use closest here. 

有什麼事我是你的關閉按鈕"chairmanClose"裏面這個div "chairmanContent"所以在這種情況下你有t Ø用.closest()遍歷你的div。


可以簡化你的代碼是這樣的:

<script type="text/javascript"> 
jQuery(document).ready(function($) { 
    $(".chairmanContent").hide(); 
    //toggle the componenet with class msg_body 
    $(".chairmanReadmore").click(function(){ 
    $(this).next(".chairmanContent").slideToggle(500); 
    }); 

    //toggle the componenet with class msg_body 
    $(".chairmanClose").click(function(){ 
    $(this).closest(".chairmanContent").slideUp(500); 
    }); 
}); 
</script> 

你並不需要兩個jQuery(document).ready();功能,而不是它,你可以做一個單一的文檔準備好方法,你可以用你的$標誌作爲我建議的jQuery的別名。

+0

這一個完美的工作!謝謝。這是否意味着當您想要在劇本中反轉動作時,我們使用.closest?對不起,如果我的問題似乎有點文字。 –

+0

看看你是否是一個elem的最外層,並且你想要像'ul li ul'這樣的元素的大孩子,如果你想要將'ul'中的第二個'ul'作爲目標,你可以使用'.find()'同樣的方法,如果你已經在孩子或大孩子elem中做了一些事件,那麼你必須用'.closest()'來遍歷你想要瞄準的元素。 – Jai

+0

謝謝你的解釋@Jai ..非常感謝。乾杯 –

0

我希望我完全理解,我寫的示例代碼爲您和不具有使用效果基本show()

檢查請:http://jsfiddle.net/mehmetakifalp/m9RE4/

$(".toggleSlide").click(function(){ 
     $(".content").slideToggle(); 
    }); 

    $(".closeContent").click(function(){ 
     $(".content").slideToggle(); 
    });