jjzjj

Javascript 遍历元素并将元素换成 HTML

coder 2023-08-02 原文

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

  1. 我要怎么做才能让元素不重复,目前,在无限滚动开始之前,它们会永远滚动 20 到一个“页面”,我想要的是如果数组中有 50 张图像,然后显示这些图像,一页 20 张,然后停止。
  2. 我想将 JS 放在一个单独的文件中,然后使用 PHP 循环一些结果并输出图像,是否可以以某种方式将渲染图像的 div 移出 javascript 函数?以便我可以将它们实际放入 html 的 block 中?

这是我在 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>

最佳答案

图像重复

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

其次,GenerateItems() 函数始终返回结果。

if there is 50 images in the array, then display those images, 20 to a page and then stop

这意味着 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 header 已设置)。

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

关于Javascript 遍历元素并将元素换成 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426299/

有关Javascript 遍历元素并将元素换成 HTML的更多相关文章

  1. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  5. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  6. ruby - 在哈希的键数组中追加元素 - 2

    查看我的Ruby代码:h=Hash.new([])h[0]=:word1h[1]=h[1]输出是:Hash={0=>:word1,1=>[:word2,:word3],2=>[:word2,:word3]}我希望有Hash={0=>:word1,1=>[:word2],2=>[:word3]}为什么要附加第二个哈希元素(数组)?如何将新数组元素附加到第三个哈希元素? 最佳答案 如果您提供单个值作为Hash.new的参数(例如Hash.new([]),完全相同的对象将用作每个缺失键的默认值。这就是您所拥有的,那是你不想要的。您可以改用

  7. ruby-on-rails - capybara ::ElementNotFound:无法找到 xpath "/html" - 2

    我正在学习http://ruby.railstutorial.org/chapters/static-pages上的RubyonRails教程并遇到以下错误StaticPagesHomepageshouldhavethecontent'SampleApp'Failure/Error:page.shouldhave_content('SampleApp')Capybara::ElementNotFound:Unabletofindxpath"/html"#(eval):2:in`text'#./spec/requests/static_pages_spec.rb:7:in`(root)'

  8. python - 如何读取 MIDI 文件、更改其乐器并将其写回? - 2

    我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的

  9. 「Python|Selenium|场景案例」如何定位iframe中的元素? - 2

    本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决

  10. ruby - 如何使用 Ruby 将 CSV 文件读入 HTML 表格? - 2

    我正在尝试将一个简单的CSV文件读入HTML表格以在浏览器中显示,但我遇到了麻烦。这就是我正在尝试的:Controller:defshow@csv=CSV.open("file.csv",:headers=>true)end查看:输出:NameStartDateEndDateQuantityPostalCode基本上我只获取标题,而不会读取和呈现CSV正文。 最佳答案 这最终成为最终解决方案:Controller:defshow#OpenaCSVfile,andthenreaditintoaCSV::Tableobjectforda

随机推荐