AJAX - 在更换div时平滑滑动按钮

时间:2014-02-24 22:18:38

标签: jquery css ajax

我想在点击时平滑地滑动按钮。我找到了这个jQuery .slideDown()方法,但我无法使它工作。我应该在哪里修改?

<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.0.min.js'></script>
<script>
$(document).ready(function () {
    myIdentifier = $.now();
    $.ajax({
        type: "GET",
        url: "http://www.w3schools.com/ajax/cd_catalog.xml?uniq=" + myIdentifier,
        dataType: "xml",
        success: function (xml) {
            $($(xml).find('ARTIST').get().reverse()).slice(0, 3).each(function () {
                artist = ("<p class='artist'>" + $(this).text() + "</p>");
                $(artist).hide().appendTo("#myDiv").fadeIn(1000);
            });
            var ii = 4;
            $('button').click(function () {
                $($(xml).find('ARTIST').get().reverse()).slice(ii, ii + 5).each(function () {
                    artist = ("<p class='artist' style='display:none;'>" + $(this).text() + "</p>");
                    $("#myDiv").append(artist);
                    $('.artist').fadeIn(1000, function () {
                        $(this).css({'visibility':'visible',display:'block'}).slideDown();
                    });

                });
                ii += 5;
            });
        }
    });
});
</script>
</head>
<body>
<div id="myDiv"></div>
<button id="button1" type="button">Show More</button>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

.fadeIn函数中,$(this)指的是$('.artist')。如果要定位单击的按钮,则必须将该按钮存储在变量中,如下所示:

$('button').click(function () {

    clickedBtn = $(this); //save $(this) for later

    //removed some stuff so it's easier to read..
    $('.artist').fadeIn(1000, function () {
        clickedBtn.slideDown(); //slideDown saved element here
    }); 
    //you don't need to set element to visible with css, 
    //slideDown() does this for you
});

答案 1 :(得分:1)

$('.artist').fadeIn(1000, function () {
    $(this).css({'visibility':'visible',display:'block'}).slideDown();
});

你的$(this)在函数内(fadeIn),现在$(this)引用元素$('。artist'),而不是$('button');

要解决,您需要将其保存在变量中:

$('button').click(function() {
  btnTarget = $(this); // this reference your $('button')
  ...
  $('.artist').fadeIn(1000, function () {
    // look now:
    btnTarget.css({'visibility':'visible',display:'block'}).slideDown();
  });
})