jQuery 父兄弟选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6577228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:04:47  来源:igfitidea点击:

jQuery Parent Sibling selector

jqueryjquery-selectors

提问by K.R.

I have a HTML document like below:

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

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

The div with class="hiddenBox" is hidden by default. On clicking the "Show" link, I want to show the hidden div. I tried this but it does not work.

class="hiddenBox" 的 div 默认是隐藏的。单击“显示”链接时,我想显示隐藏的 div。我试过这个,但它不起作用。

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

The class "hiddenBox" occurs multiple times in my document, but I want only the sibling to show.

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

回答by user113716

The problem is that thisin your function won't be the <a>element. You can change your inline handler like this to fix it:

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

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

Ah just noticed, additionally you'll need to reference the thisoutside of the ready handler.

啊刚刚注意到,另外你需要引用this就绪处理程序的外部。

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

I assume you've set it up this way in case someone clicks the link before the DOM is loaded.

我假设您已经以这种方式进行了设置,以防有人在加载 DOM 之前单击该链接。

回答by AnApprentice

回答by kobe

looks like the following is wrong

看起来以下是错误的

remove that function inside and it should work

删除里面的那个功能,它应该可以工作

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

more elegant way of doing is

更优雅的做法是

give some class to href like "test"

给一些类来 href 像“测试”

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

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

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