我有一些看起来像这样的HTML:

<ul class="faq">
    <li class="open">
        <a class="question" href="">This is my question?</a>
        <p>Of course you can, it will be awesome. </p>
    </li>
</ul>

使用CSS我将'p'标签设置为display:none;。我想在单击锚点时使用jQuery来显示或隐藏'p'标签,但我对兄弟选择器有一些麻烦。

试着让选择器工作,我试过了:

$("a.question").click(function () {
    $(this + " ~ p").css("background-color", "red");
});

测试它。看起来,兄弟选择器不能真正像这样使用,因为我对jQuery完全不熟悉,我不知道实现这种情况的适当方法。

提前致谢!

有帮助吗?

解决方案

尝试使用:

$(this).siblings('p').css()

其他提示

$(this).next("p").css("...")

“p”如果您只想要DOM中的下一个非空白节点,则上面是可选的。

  

我想在点击锚点时使用jQuery显示或隐藏'p'标签

由于您提到在单击锚点时要切换'p'标记,我会这样做:

  $("a.question").click(function (event) {
      $(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element
      event.preventDefault(); //stop the browser from following the link
  });      
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top