如何通过jQuery显示隐藏的内容块

时间:2013-03-06 18:31:11

标签: jquery css hide show

我有以下html:

<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都没有工作。

有人可以帮忙吗?

感谢。

2 个答案:

答案 0 :(得分:4)

因为您的按钮被封装在DIV中,所以它不会使用.closest()或.find()。您已经点击了该按钮,可以使用$(this)并使用.parent()然后.next()从那里导航:

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

那应该有用。这也应该消除不必要的变量:

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

答案 1 :(得分: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();
});
相关问题