了解jQuery

Ric*_*haw 3 javascript jquery

好吧,我正在设计一个网站,并认为我会坚持一些jQuery,因为我真的需要这样的经验.

有问题的页面在这里:http://new.focalpix.co.uk/moreinfo.php

有问题的JS是:

$(document).ready(function(){

    $(".answer").css("display","none");

    $("#maincontent a.animate").click(function() {
        $("#maincontent .answer").slideUp('slow');
        var id = $(this).attr('href');
        $(id).slideDown('slow');
        return false;
    });

});
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,但是如果您点击答案已经滑落​​的链接,那么它会向上滑动,然后再次向下滑动.

我不确定以最干净的方式阻止这种情况发生 - 任何想法?

Sov*_*iut 7

您应该使用.slideToggle()效果.

$(document).ready(function() {
    $(".answer").css("display","none");
    $("#maincontent a.animate").click(function() {
        $("#maincontent .answer").slideToggle('slow');
    });
});
Run Code Online (Sandbox Code Playgroud)


yaa*_*uie 5

首先,我建议您的常见问题解答的结构如下:

<div id="faq">
  <div class="qa" id="faq_greenandflies">
    <span class="q">What is <a href="#faq_greenandflies">green and flies</a></span>
    <div class="a">
      Super Pickle!
    </div>
  </div>
  <div class="qa" id="faq_redandbadforteeth">
    <span class="q">What is <a href="#faq_redandbadforteeth">Red and bad for your teeth</a></span>
    <div class="a">
      a Brick
    </div>
  </div>
  <!--
  More FAQ's here

  -->
</div>
Run Code Online (Sandbox Code Playgroud)

然后按如下方式定义jQuery:

 <script type="text/javascript">
    $(function(){
  // hide all answers
  $('div#faq .qa .a').hide();

      // bind a click event to all questions
  $('div#faq .qa .q a').bind(
        'click',
        function(e){
          // roll up all of the other answers (See Ex.1)
          $(this).parents('.qa').siblings().children('.a').slideUp();
          // reveal this answer (See Ex.2)
          $(this).parents('.qa').children('.a').slideDown();
          // return true to keep any other click events       
          return true;
        });

      // check location.hash to see if we need to expand one (direct link)
      $(location.hash).find('.q a').click();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

说明:

(实施例1,)

  • 是被点击的链接
  • 获取包含元素的元素并具有"qa"类(包含问题和答案的框)
  • 选择所有的兄弟姐妹.(我们现在将所有qa作为jQ对象)
  • 隐藏答案

(例2)

  • 是单击的行或链接
  • 获取包含元素的元素并具有"qa"类(包含问题和答案的框)
  • 揭示答案

一个有效的演示在这里.

这为你做了几件事:

  • 如果用户深层链接到答案,则会自动显示答案
  • 如果用户单击一个答案,则隐藏所有其他答案
  • 你可以给你的div正确的id,这有助于搜索引擎优化链接到个别答案