使用append添加项目后的jQuery淡入

1 ajax jquery append fadein

请有人把我从我的痛苦中解脱出来......我每小时都在倾诉......

我(这是缩写)创建了一个函数,使用append将页面添加到页面.问题是一旦添加了fadeIn函数就不起作用了. 但是,如果我将元素硬编码到页面,它将工作:

这是我的javascript:

          //Loop through the images and print them to the page
      for (var i=0; i < totalBoxes; i++){
          //$("p").add(arr).appendTo('#bg');
          $.ajax({
              url: "random.php?no=",
              cache: false,
              success: function(html){
                $(html).fadeIn(html).appendTo('#bg');
              }
          });
      }

    //Choose the image to be faded in
        $(".pf-box img").hover(function(){
        var largePath = $(this).attr("rel");
            $(this).fadeOut("slow", function() {
                    $(this).attr({ src: largePath }).fadeIn("slow");
            });
            return false;
        }); 
Run Code Online (Sandbox Code Playgroud)

random.php字面上印刷了很多盒子......这里是一个打印样本:

<div class="pf-box" style="">
<a href="#">
This is where the image is printed with the rel attribute on the image tag. (stackoverflow didnt allow the posting of the img tag because its my first post)
</a>
</div>
Run Code Online (Sandbox Code Playgroud)

Fun*_*nka 5

看起来您的fadeIn功能参数不正确.我认为您还需要在将文档淡入之前将html附加到文档中.

试试这个,在你的成功函数中?

function(html) {
    $('#bg').append(html).fadeIn('slow');
}
Run Code Online (Sandbox Code Playgroud)

您也可以找到fadeIn 的doc页面.

祝好运!


编辑/ UPDATE

好吧,我想我知道你现在要做什么.修复上面描述的语句(追加然后淡入)后,您需要做的是在ajax检索/追加有机会完成分配您的hover事件.

发生的事情是你的第一个代码块正在向网络服务器发出大量异步请求以获取你想要的图像.然后,在第一个块"完成"之后立即,但(重要的是!)在这些请求有机会完成之前,您的第二个代码块(尝试)执行.它正在寻找选择器".pf-box img"来尝试添加hover事件,但问题是,这些图像在页面上还不存在!

您需要做的是等待图像从服务器返回,然后再尝试选择它们或向它们添加事件.这是通过回调完成的,你已经在你的success函数中部分工作了...

(请注意,我没有测试过这个,它只是为了证明...)

// Loop through the images and print them to the page.
// Attach hover event within the callback, after image has been added.
for (var i=0; i < totalBoxes; i++){
    $.ajax({
        url: "random.php?no=",
        cache: false,
        success: function(html) {
            // following line I originally suggested, but let's make it better...
            //$('#bg').append(html).fadeIn('slow');
            // also note the fine difference between append and appendTo.
            var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
            $('img', $d).hover(function() {
                var largePath = $(this).attr("rel");
                $(this).fadeOut("slow", function() {
                    $(this).attr({ src: largePath }).fadeIn("slow");
                });
            });
        }
    });
}
Run Code Online (Sandbox Code Playgroud)