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

时间:2009-11-04 00:54:51

标签: jquery ajax 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;
        }); 

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>

2 个答案:

答案 0 :(得分:5)

您的fadeIn函数的参数看起来不正确。我想你也可以在将文件淡入之前将html附加到你的文档中。

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

function(html) {
    $('#bg').append(html).fadeIn('slow');
}

您还可以找到fadeIn的doc页面。

祝你好运!

<小时/>

EDIT / UPDATE

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

正在发生的事情是,您的第一个代码块正在向Web服务器发出一堆异步请求,以获取您想要的图像。然后,在第一个块“完成”之后立即,但(重要的是!)在这些请求有机会完成之前,您的第二个代码块(尝试)执行。它正在寻找选择器“.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");
                });
            });
        }
    });
}

答案 1 :(得分:1)

您误解了fadeIn方法。

fadeIn对现有元素进行操作,并动画元素的不透明度,就像fadeOut一样。您希望将HTML附加到#bg元素,然后将其淡入。

例如:

                      success: function(html){
                            $(html).appendTo('#bg').fadeIn("slow");
                      }