jQuery Parent Sibling选择器

时间:2011-07-05 01:17:38

标签: jquery jquery-selectors

我有一个HTML文档,如下所示:

<td>
  <div class="commentLink">
    <a href="javascript:ShowBox()">Show</a>
  </div>
  <div class="hiddenBox">
    <!-- Hidden content  -->
  </div>
</td>

默认情况下隐藏class =“hiddenBox”的div。单击“显示”链接,我想显示隐藏的div。我尝试了这个,但它不起作用。

function ShowBox() {
 $(function(){
  $(this).parent().siblings(".hiddenBox").show();
 });
}

类“hiddenBox”在我的文档中多次出现,但我只想显示兄弟姐妹。

3 个答案:

答案 0 :(得分:18)

问题是您的函数中的this不是<a>元素。您可以像这样更改内联处理程序来修复它:

<a href="#" onclick="ShowBox.call(this); return false;">Show</a>

我刚注意到,另外你需要在就绪处理程序之外引用this

function ShowBox() {
   var that = this;
   $(function(){
       $( that ).parent().siblings(".hiddenBox").show();
   });
}

我假设您已经这样设置,以防有人在加载DOM之前点击链接。

答案 1 :(得分:5)

答案 2 :(得分:0)

看起来以下是错误的

删除内部的该功能,它应该工作

function ShowBox() {
  $(this).parent().siblings(".hiddenBox").show();
}

更优雅的做法是

给某些类href像“test”

 <a class="test">Show</a>

$('.test').click(function() {

    $(this).parent().siblings(".hiddenBox").show();
         return false;
});