简体   繁体   English

单击链接时显示相关的div

[英]Show related div when link is clicked

I created a ul containing li elements. 我创建了一个包含li元素的ul I want to to slide down a div when a link in the same li is clicked. 当我单击同一li的链接时,我想向下滑动div

The problem is when I click the link all div s are shown. 问题是当我单击链接时,将显示所有div

I use PHP for setting the id on each link. 我使用PHP在每个链接上设置ID。

The html code is here: html代码在这里:

  <li class='post'>
    <div class='link'>
      <a href='#'id=". * Here is Post ID * ."></a>
    </div>
    <div class='slidedown'>//here is what I want to sliding</div>
  </li>

The jQuery code is here : jQuery代码在这里:

$(".link a").click(function(){

    var id_post = $(this).attr("id");

    $(".slidedown").slideDown("slow");

    return false;
});

Use .parent() to move up one parent. 使用.parent()向上移动一位。 Since the container were looking for is the .post we'll have to move up 2 parents. 由于容器正在寻找的是.post我们必须将2个父母向上移动。 Then we can find the child of it that is .slidedown and slide that one down with .slideDown() 然后我们可以找到它的子级.slidedown ,然后使用.slideDown()将其向下滑动

$(".link a").click(function(){

    $(this).parent().parent().children('.slidedown').slideDown("slow");

});

You can do it even more easy: 您可以更轻松地做到这一点:

jQuery jQuery的

$('.link').on('click', function() {
    $(this).parent().find('.slidedown').slideDown('slow');
});

Or you use: 或者您使用:

$('.link a').on('click', function() {
    $(this).closest('.slidedown').slideDown('slow');
});

Go to .closest() or .parent() at jQuery Docs to learn more. 转到jQuery Docs的.closest().parent()了解更多信息。

Here's the code that works well: 这是运行良好的代码:

$(".link").click(function(){
     $(this).siblings('.slidedown').slideDown('slow');
});

You can use parent() to move up a level and next() to target the next sibling: 您可以使用parent()向上移动一个级别,然后使用next()来定位下一个同级对象:

$(".link a").click(function(){
  $(this).parent(".link").next(".slidedown").slideDown("slow");
  return false;
});

Or you can access the .post using closest() and target the .slidedown using find() or children() : 或者,您可以使用.slidedown closest()访问.post并使用find()children()定位.slidedown

$(".link a").click(function(){
  $(this).closest(".post").find(".slidedown").slideDown("slow");
  return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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