使用jquery

时间:2017-03-12 01:08:25

标签: javascript jquery html css toggle

当"专辑1"单击链接我想在隐藏和显示照片之间切换。但是,现在它根本没有做任何事情。我试图在控制台中调试它,但它没有输出任何有用的东西。

的script.js

$(document).ready(function() {
    // album click toggle
    $('.album a').click(function() {
        console.log($(this).parent().find(".photos"));
        $(this).parent().find(".photo").hide();
    });
});

的index.html

<div class="album">
            <h2><a href="#">Album 1</a></h2>
            <ul class="photos">
                <li>
                    <img src="img/img1.jpg">
                    <span class="info"><span>Image 1</span></span>
                </li>
                <li>
                    <img src="img/img2.jpg">
                    <span class="info"><span>Image 2</span></span>
                </li>
                <li>
                    <img src="img/img3.jpg">
                    <span class="info"><span>Image 3</span></span>
                </li>
            </ul>
        </div>

2 个答案:

答案 0 :(得分:0)

您的目标是.photo而不是.photos

除此之外,您实际上可以切换,如:

jQuery(function($) {

  // album click toggle
  $('.album a').click(function(e) {
    e.preventDefault(); // Prevent browser scroll to top
    $(this).closest(".album").find(".photos").stop().slideToggle();
  });
  
  
});
*{margin:0; box-sizing:border-box;}

.album ul  {display:none; list-style:none; padding:0; margin:0; overflow:auto;}
.album li  {display:inline-block; vertical-align:top;}
.album li>*{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="album">
  <h2><a href="#">Album 1</a></h2>
  <ul class="photos">
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 1</span></span>
    </li>
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 2</span></span>
    </li>
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 3</span></span>
    </li>
  </ul>
</div>

<div class="album">
  <h2><a href="#">Album 2</a></h2>
  <ul class="photos">
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 1</span></span>
    </li>
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 2</span></span>
    </li>
    <li>
      <img src="//placehold.it/64x50">
      <span class="info"><span>Image 3</span></span>
    </li>
  </ul>
</div>

答案 1 :(得分:-1)

你的$(this).parent()是指h2

并且'.photos'不是'.photo'

$(document).ready(function() {
        // album click toggle
        $('.album a').click(function() {
            console.log($(this).parent().parent().find(".photos"));
            $(this).parent().parent().find(".photos").hide();
        });
    });

$(document).ready(function() {
            // album click toggle
            $('.album a').click(function() {
                console.log($(this).parents().find(".photos"));
                $(this).parents().find(".photos").hide();
            });
        });