2013-03-06 62 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