2013-03-06 28 views
0
顯示隱藏的內容區塊

我有以下的html:如何通過jQuery

<div class="contentBlock"> 
    <div><img src="images/help.png" alt="help button" class="helpButton"></div> 
    <div class="helpBlock"> 
    <p>...some hidden text...</p> 
    </div> <!-- end .helpBlock --> 
    <h2>A Header</h2> 
    <p>...some visible text...</p> 
</div> <!-- end .contentBlock --> 

我有以下的CSS:

div.contentBlock { 
    position: relative; /* required for z-index */ 
    z-index: 1; /* interacts with div.helpBlock */ 
} 
div.helpBlock { 
    display: none; 
    position: relative; /* required for z-index */ 
    z-index: 10; /* interacts with div.contentBlock */ 
} 

我有以下的jQuery:

$(document).ready(function() { 
    // Show helpBlock on page 
    $('img.helpButton').click(function(){ 
    /*$(this).closest('.helpBlock').show();*/ // does not work 
    /*$(this).closest('.helpBlock').css('display');*/ // does not work 
    var $contentWrapper = $(this).closest('.helpBlock'); 
    var $siblings = $contentWrapper.siblings('.helpBlock'); 
    $siblings.find('.helpBlock').show(); // does not work 
    }); 
    // end Show helpBlock 
}) // end jQuery Functions 

我試圖讓我.helpBlock顯示,當我點擊幫助按鈕,但沒有我的jquery工作。

任何人都可以協助嗎?

THanks。

回答

4

由於您的按鈕被封裝在DIV中,因此它不會使用.closest()或.find()。您已經點擊按鈕,就可以使用$(this)並從那裏導航與.parent()然後.next()

$(this).parent().next('.helpBlock').show(); 

這應該工作。這也應消除不必要的變量:

var $contentWrapper = $(this).closest('.helpBlock'); 
var $siblings = $contentWrapper.siblings('.helpBlock'); 
+0

優秀。謝謝@LifeInTheGrey。這工作! – 2013-03-06 18:35:54

+0

不要感謝我,謝謝複選標記。 ;) – PlantTheIdea 2013-03-06 18:36:22

+0

請考慮標記這個答案與複選框,以顯示如果解決您的問題:) – 2013-03-06 18:38:03

1

試試這個:

$('img.helpButton').click(function(){ 
    var $contentWrapper = $(this).parent(); 
    var $siblings = $contentWrapper.siblings('.helpBlock'); 
    $siblings.show(); 
}); 

如果你想要一個襯墊:

$('img.helpButton').click(function(){ 
    $(this).parent().siblings('.helpBlock').show(); 
}); 
+0

好的,謝謝@Jai。我要和LifeInTheGrey的回答一起去,因爲我已經嵌入了它,它的運作加上它在語法上更輕。 – 2013-03-06 18:37:20

+0

好吧很好,但你可以把它做成一個班輪。 – Jai 2013-03-06 18:38:12