使用 jQuery Cycle 和 ajax 动态创建幻灯片放映 - 图像不会立即加载

发布于 2024-09-12 17:25:41 字数 2140 浏览 7 评论 0原文

我目前正在尝试为客户制作一个廉价、简单的幻灯片导航框(类似于 Red Sox 或 Gamespot 在其网站上使用的内容,但要简单得多)。到目前为止,它实际上进展顺利,但有一个问题 - 第一次访问时图像不会出现。它们仅在页面重新加载后出现。我认为这可能是某种运行时问题,或者可能是缓存问题,但我不确定如何解决它。我的代码:

PHP:

if (isset($_GET['start']) && "true" === $_GET['start'])
{
    $images = array();

    if ($dir = dir('images'))
    {
        //$count = 0;

        while(false !== ($file = $dir->read()))
        {
            if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
            {
                $lastModified = filemtime("{$dir->path}/$file");
                $images[$lastModified] = $file;
                //$images["image$count"] = $file;
                //++$count;
            }
        }

        echo json_encode($images);
    }
    else { echo "Could not open directory"; }
}

HTML 和 JavaScript:

<!doctype html>
<html lang="en-us">
    <head>
        <title>jQuery Cycle test</title>
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>
        <style>
            #slideshow a { margin: 0; padding: 0; color: #fff; }
        </style>
    </head>

    <body>
        <div id="slideshow">
        </div>
    </body>

    <script type="text/javascript">
        $.get('slideshow.php', {start : "true"}, function(data){
            var images = JSON.parse(data);

            for(var image in images){
                $('#slideshow').append('<a href="images/' + images[image] + '"><img src="images/' + images[image] + '" alt="" /></a>');
            }

            $('#slideshow').cycle({
                fx: 'cover',
                direction: 'right',
                timeout: 3000,
                speed: 300
            });
        });
    </script>

</html>

我想我可能需要延迟循环函数的时间,或者以某种方式强制它第一次“看到”图像。我只是不知道该怎么做。

I'm currently trying to make a cheap, simple slide show navigation box for a client (something along the lines of what, say, the Red Sox or Gamespot use on their sites, but far, far simpler). So far, it's actually coming along nicely, with one problem - the images don't appear upon a first visit. They only appear after the page is reloaded. I think it may be some sort of runtime issue, or perhaps a cache issue, but I'm not sure how to fix it. My code:

PHP:

if (isset($_GET['start']) && "true" === $_GET['start'])
{
    $images = array();

    if ($dir = dir('images'))
    {
        //$count = 0;

        while(false !== ($file = $dir->read()))
        {
            if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
            {
                $lastModified = filemtime("{$dir->path}/$file");
                $images[$lastModified] = $file;
                //$images["image$count"] = $file;
                //++$count;
            }
        }

        echo json_encode($images);
    }
    else { echo "Could not open directory"; }
}

HTML and JavaScript:

<!doctype html>
<html lang="en-us">
    <head>
        <title>jQuery Cycle test</title>
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>
        <style>
            #slideshow a { margin: 0; padding: 0; color: #fff; }
        </style>
    </head>

    <body>
        <div id="slideshow">
        </div>
    </body>

    <script type="text/javascript">
        $.get('slideshow.php', {start : "true"}, function(data){
            var images = JSON.parse(data);

            for(var image in images){
                $('#slideshow').append('<a href="images/' + images[image] + '"><img src="images/' + images[image] + '" alt="" /></a>');
            }

            $('#slideshow').cycle({
                fx: 'cover',
                direction: 'right',
                timeout: 3000,
                speed: 300
            });
        });
    </script>

</html>

I think I may need to delay the timing of the cycle function, or perhaps somehow force it to 'see' the images the first time through. I'm just not sure how to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

智商已欠费 2024-09-19 17:25:41

有两个可能的原因(或者我遗漏的更多原因)导致它加载异常:

  1. 您的调用未包含在 document.ready 中(即使您的 JavaScript 代码位于页面底部) - 这可能不是问题......只是一个想法。

    即创建一个函数来保存您的加载并执行以下操作:

    $(文档).ready(function(){
        加载图像();
        开始幻灯片放映();
    });
    
  2. 另一件事可能是在第一次加载时,图像尚未下载到您的浏览器。在显示循环组件之前,您可以检查所有图像是否已完成加载(使用计数器并在所有图像上加载等)。这可以修复 Chrome 的问题。

笔记:
内置的 .each 比“for”循环快得多。 (特别是对于 IE 和许多项目...)

例如:

$(newImages).each(function(){
    $('#slideshow').append($(this));
});

There are two possible reasons (or more that I am missing) that it could be loading oddly:

  1. Your call isn't encompassed in a document.ready (even though your JavaScript code is at the bottom of the page) - this might not be the issue... just a thought.

    i.e. create a function to hold your loading and do a:

    $(document).ready(function(){
        loadImages();
        startSlideShow();
    });
    
  2. The other thing could be that on the first load, the images haven't downloaded to your browser. You could do a check to see if all the images have finished loading (use a counter and isloaded on all images etc.) before you show the cycle component. This could fix it for Chrome.

Note:
The built-in .each is way way faster than a "for" loop. (specially for IE and many items...)

For example:

$(newImages).each(function(){
    $('#slideshow').append($(this));
});
因为看清所以看轻 2024-09-19 17:25:41

自从我写了原来的答案后,我发现即使超时也会出现同样的问题。我在 jQuery 论坛上与该插件的开发人员交谈,他的工作示例使用 $.getJSON 而不是 $.get。我改用了它,效果非常好。我只能假设 $.getJSON 解析数据的方式与我手动调用解析函数的方式之间存在一些细微的差别。无论是实际的代码问题还是解析完成的时间问题仍然是个谜。

我的解决方案:

<!doctype html>
<html lang="en-us">
    <head>
        <title>jQuery Cycle test</title>
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>

        <style>
            #slideshow a { margin: 0; padding: 0; color: #fff; display: block; }
            img { width: 305px; height: 278px; }
        </style>
    </head>

    <body>
        <div id="slideshow">
        </div>
    </body>

    <script type="text/javascript">     
        $.getJSON('slideshow.php', function(images){
            for(var i = 0; i < images.length; ++i){
                $('#slideshow').append('<a href="images/' + images[i]['src'] + '"><img src="images/' + images[i]['src'] + '" alt="" /></a>');
            }

            $('#slideshow').cycle({fx: 'cover', direction: 'right', timeout: 3000, speed: 300});
        });
    </script>

</html>

Since I wrote the original answer, I found that the same problem was occurring even with the timeout. I talked to the developer of the plugin on the jQuery forums, and his working example used $.getJSON rather than $.get. I switched to that, and it worked perfectly. I can only assume that there's some slight, subtle difference between how $.getJSON parses data and how I was doing it with the manual invocation of the parse function. Whether it's an actual code issue or timing issue of when the parsing is done remains a mystery.

My solution:

<!doctype html>
<html lang="en-us">
    <head>
        <title>jQuery Cycle test</title>
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>

        <style>
            #slideshow a { margin: 0; padding: 0; color: #fff; display: block; }
            img { width: 305px; height: 278px; }
        </style>
    </head>

    <body>
        <div id="slideshow">
        </div>
    </body>

    <script type="text/javascript">     
        $.getJSON('slideshow.php', function(images){
            for(var i = 0; i < images.length; ++i){
                $('#slideshow').append('<a href="images/' + images[i]['src'] + '"><img src="images/' + images[i]['src'] + '" alt="" /></a>');
            }

            $('#slideshow').cycle({fx: 'cover', direction: 'right', timeout: 3000, speed: 300});
        });
    </script>

</html>
想念有你 2024-09-19 17:25:41

知道如何让它与常规获取一起工作吗?这就是我正在使用的:

    $.get(loadUrl, { id: id },
     function(data){
          $('#loader').remove();
             window.scrollTo(0,0);
          $('#display').html(data);             
          startCycle();
          });

function startCycle() {
     //trigger cycle
     $('.images').cycle({
          fx:     'fade',
          speed:  500,
          timeout: 0,
          pager: '#sub-nav .root',
          prev: "#sub-nav .prev",
          next: "#sub-nav .next",
          before: onAfter
      });

     $("#sub-nav a:first").addClass("first");
} //start cycle

ajax 返回的内容是一组图像以及一些文本内容。

Any idea how to get it to work with a regular get? This is what I am using:

    $.get(loadUrl, { id: id },
     function(data){
          $('#loader').remove();
             window.scrollTo(0,0);
          $('#display').html(data);             
          startCycle();
          });

function startCycle() {
     //trigger cycle
     $('.images').cycle({
          fx:     'fade',
          speed:  500,
          timeout: 0,
          pager: '#sub-nav .root',
          prev: "#sub-nav .prev",
          next: "#sub-nav .next",
          before: onAfter
      });

     $("#sub-nav a:first").addClass("first");
} //start cycle

The content that is being returned by ajax is a group of images as well as some text content.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文