1

请有人把我从我的痛苦中解脱出来……我一小时又一小时地倾注于此……

我(这是缩写)一直在创建一个函数,它使用 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>
4

2 回答 2

5

看起来您的fadeIn函数的参数不正确。我认为您还希望在淡入之前将 html 附加到您的文档中。

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

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

您可能还会发现 fadeIn 的文档页面很有帮助。

祝你好运!


编辑/更新

好的,我想我知道你现在想要做什么。在您修复了我上面描述的语句(追加然后淡入)之后,您需要做的是在 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");
                });
            });
        }
    });
}
于 2009-11-04T00:57:51.153 回答
1

你误解了fadeIn方法。

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

例如:

                      success: function(html){
                            $(html).appendTo('#bg').fadeIn("slow");
                      }
于 2009-11-04T01:03:47.560 回答