简体   繁体   English

结合使用“ this”和jQuery Selectors

[英]Using “this” with jQuery Selectors

I have some HTML that looks like this: 我有一些看起来像这样的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>

Using CSS I'm setting the p tag to display:none; 使用CSS我将p标签设置为display:none; . I want to use jQuery to display or hide the p tag when the anchor is clicked, but I'm having some troubles with the sibling selector. 单击anchor时,我想使用jQuery显示或隐藏p标签,但是同级选择器遇到了一些麻烦。

Just trying to get the selector working, I tried: 只是试图使选择器工作,我尝试过:

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

to test it out. 测试一下。 Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen. 看来,同级选择器实际上不能像那样使用,而且由于我是jQuery的新手,所以我不知道实现该目标的适当方法。

尝试使用:

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

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

I want to use jQuery to display or hide the 'p' tag when the anchor is clicked 我想使用jQuery在单击锚点时显示或隐藏'p'标签

Since you mentioned that you'd like to toggle the 'p' tag when the anchor is clicked, I'd do: 既然您提到您想在单击锚点时切换'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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM