【问题标题】:Javascript looping over items and swapping out items into HTMLJavascript循环项目并将项目换成HTML
【发布时间】:2017-11-22 03:25:58
【问题描述】:

我正在使用从 CodePen 找到的以下代码...我在 JS 方面很糟糕,我希望有人可以帮助我。

  1. 如何使项目不重复,目前,在无限滚动开始之前,它们以 20 永远滚动到一个“页面”,我想要的是如果数组中有 50 个图像,然后显示这些图像,20 到一页然后停止。
  2. 我想将 JS 放在一个单独的文件中,然后使用 PHP 循环一些结果并输出图像,是否可以以某种方式将呈现图像的 div 从 javascript 函数中移出?这样我就可以将它们实际放入 html 的块中?

这是我在 HTML 部分的代码

<div id="SlideMiddle">
    <div id="grid">
        <div id="grid-content"></div>
    </div>
</div>

这是javascript

<script>
    var Imgs = [
        'https://tympanus.net/Development/GridLoadingEffects/images/1.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/3.jpg',
        'https://d13yacurqjgara.cloudfront.net/users/64706/screenshots/1167254/attachments/152315/SUGARSKULL-01.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/8.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/10.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/14.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/9.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/13.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/12.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/4.jpg',
        'http://www.thedrum.com/uploads/news/172673/DzrMPF_DeezerPoster_MusicSoundBetterWithYou_03.jpg'
    ];

    $(document).ready(function(){
        $grid = $('#grid-content');

        $.fn.revealItems = function($items){

            var iso = this.data('isotope');
            var itemSelector = iso.options.itemSelector;
            $items.hide();
            $(this).append($items);
            $items.imagesLoaded().progress(function(imgLoad, image){
                var $item = $(image.img).parents(itemSelector);
                $item.show();
                iso.appended($item);
            });

            return this;
        }
        $grid.isotope({
            containerStyle: null,
            masonry:{
                columnWidth: 300,
                gutter: 15
            },
            itemSelector: '.grid-item',
            filter : '*',
            transitionDuration: '0.4s'
        });


        $grid.imagesLoaded().progress(function(){
            $grid.isotope();
        })

        function GenerateItems(){
            var items = '';
            for(var i=0; i < 20; i++){
                items += '<div class="grid-item c'+(i%9)+' wow fadeInUp" ><a href=""><img src="'+Imgs[i%Imgs.length]+'" /></a></div>';
            }
            return $(items);
        }

        // SimpleInfiniteScroll
        function Infinite(e){
            if((e.type == 'scroll') || e.type == 'click'){
                var doc = document.documentElement;
                var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
                var bottom = top + $(window).height();
                var docBottom = $(document).height();

                if(bottom + 50 >= docBottom){
                    $grid.revealItems(GenerateItems());
                }
            }
        }

        $grid.revealItems(GenerateItems());

        $(window).resize(function(){
            var margin=40;
            var padding=15;
            var columns=0;
            var cWidth=300;
            var windowWidth = $(window).width();

            var overflow = false;
            while(!overflow){
                columns++;
                var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
                if(WidthTheory > windowWidth)
                    overflow = true;
            }
            if(columns > 1)
                columns--;

            var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);

            if( GridWidth != $('#grid').width()){
                $('#grid').width(GridWidth);
            }
        });
        $(window).scroll(Infinite);
        new WOW().init();

    })
</script>

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    图像重复

    有两件事会导致图像重复行为。首先,正如另一个答案中所指出的,循环计数器被硬编码为 20。因此,如果您传入五张图像,每张图像将重复四次。将 20 更改为 Imgs 数组的长度可以防止这种情况发生。

    其次,GenerateItems() 函数总是返回结果。

    如果数组中有 50 个图像,则显示这些图像,20 个到一页然后停止

    这意味着GenerateItems() 在显示所有 50 张图像后将需要返回一个空集(或不被调用)。一种天真的方法可能涉及全局页面计数变量。 In this codepen,我加了这样一个变量来限制页数,像这样:

    var pagesServed = 0;
    
    $(document).ready(function(){ 
        $grid = $('#grid-content');
    .....
    function GenerateItems(){
        console.log("generating items");
        var items = '';
        if (++pagesServed > 2) {
           return items; 
        }
        for(var i=0; i < Imgs.length; i++){
          ....
    

    服务器端渲染

    在现实生活中的用例中,您可能正在从您的服务器获取此图像链接列表,这与您问题的第二部分有关。

    您可以轻松地在服务器端呈现这些 div。 GenerateItems() 函数将对您的后端进行 AJAX 调用以获取 div,而不是在 javascript 中构建它们。该 PHP 代码可能如下所示:

    <?php
    require_once __DIR__.'/vendor/autoload.php';
    
    session_start();
    
    $Imgs = [
        'https://tympanus.net/Development/GridLoadingEffects/images/1.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/3.jpg',
        'https://d13yacurqjgara.cloudfront.net/users/64706/screenshots/1167254/attachments/152315/SUGARSKULL-01.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/8.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/10.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/14.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/9.jpg',
        'https://tympanus.net/Development/GridLoadingEffects/images/13.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/12.png',
        'https://tympanus.net/Development/GridLoadingEffects/images/4.jpg',
        'http://www.thedrum.com/uploads/news/172673/DzrMPF_DeezerPoster_MusicSoundBetterWithYou_03.jpg'
    ];
    
    $items = '';
    
    for ($i=0; $i < 20; $i++){
        $items .= '<div class="grid-item c' . ($i % 9) . ' wow fadeInUp" ><a href=""><img src="' . $Imgs[$i % count($Imgs)] . '" /></a></div>';
    }
    header('Access-Control-Allow-Origin: *');
    printf($items);
    

    那么GenerateItems() 大概是这样的:

      function GenerateItems(){
          console.log("generating items");
          var fetched =  fetch('http://localhost:8000').then(function(data) {
              return data.text();
          });
    
          return fetched;
        }
    

    revealItems被修改为处理Promise:

    $.fn.revealItems = function($items){
        var self = this;
        var iso = this.data('isotope');
        var itemSelector = iso.options.itemSelector;
        $items.then(function($fetcheditems) {
            console.log($fetcheditems);
            $($fetcheditems).hide();
            $(self).append($fetcheditems);
            $($fetcheditems).imagesLoaded().progress(function(imgLoad, image){
                var $item = $(image.img).parents(itemSelector);
                $item.show();
                iso.appended($item);
            });
        });
        return this;
    }
    

    我放了一个在服务器端呈现这些 div 的示例on GitHub免责声明 - 这是一个最小的示例 - 我没有费心让 WOW 样式工作,并且 CORS 支持很少(例如,没有设置 Access-Control-Allow-Credentials 标头)。

    您需要实现自己的服务器端逻辑来决定在每次调用时返回哪些图像。例如,您可以使用 session 来跟踪已经提供了哪些图像,或者您可以接受定义所请求图像范围的查询字符串参数。

    【讨论】:

    • codepen.io/anon/pen/WXgvjR 这是我创建的代码笔......我想要做的是从 JS 内部移动 div 创建,在 html 中手动列出它们,在 grid-content div ,这样我就可以使用 PHP 进行一些分页,还可以添加动态标签。我还希望它们按顺序显示而不是随机显示
    【解决方案2】:
    1. 对于第一个问题,我会更改 GenerateItems 程序

      function GenerateItems(){
          var items = '';
          var limit = Imgs.length > 20 ? 20 : Imgs.length;
          for(var i=0; i < limit; i++){
              items += '<div class="grid-item c'+(i%9)+' wow fadeInUp" ><a href=""><img src="'+Imgs[i%Imgs.length]+'" /></a></div>';
          }
          return $(items);
      }
      

    但是您能否提供 plunter 或 Codepen 的样式示例?

    1. 如果我理解正确,您需要在此处输入选择器并生成图像?

    a) 然后从 JS 文件中定义函数:

    function infiniteList(selector){
        $grid = $(selector);
    

    ..... }

    b) 在 index.html 头文件中附加 JS 文件

    var selector = ...//some calculation to get selector
    $(document).ready(infiniteList(selector));
    

    【讨论】:

    • codepen.io/anon/pen/WXgvjR 这是我创建的代码笔......我想要做的是从 JS 内部移动 div 创建,在 html 中手动列出它们,在 grid-content div 中,这样我就可以使用 PHP 进行一些分页,还可以添加动态标签。我还希望它们按顺序显示而不是随机显示
    【解决方案3】:

    对于第一个问题,我认为您只想摆脱无限滚动。 检查这里-https://codepen.io/anon/pen/mqawpy 只需注释行号。 117 笔。

    //$(window).scroll(Infinite);
    

    其次,您可以使用标签插入 HTML 内容,即使用 PHP 的 HTML 的“...”标签。 在这里查看-How to write html code inside <?php ?>

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 2015-02-23
      • 2013-10-24
      相关资源
      最近更新 更多