You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JSON在Justified Gallery中展示图片?代码问题求助

修复Justified Gallery加载JSON图片的问题

原代码存在的问题:

  • 未正确解析JSON结构:返回的JSON是包含photo数组的顶层对象,原代码直接遍历整个对象,应该遍历photo.photo数组
  • 模板字符串语法错误:混用了模板字符串与传统字符串拼接,变量引用方式完全错误
  • Justified Gallery初始化时机错误:在循环内重复初始化插件,导致性能问题与渲染异常
  • 未处理JSON中URL的前后空格:部分URL包含首尾空格,会导致图片加载失败

修正后的完整代码:

<!DOCTYPE html>
<html>
<head>
    <!-- 引入依赖资源 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.8.1/css/justifiedGallery.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/colorbox.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox.min.js"></script>
</head>
<body>
    <div id="img"></div>

    <script>
        $(document).ready(function () {
            $.getJSON('https://raw.githubusercontent.com/aishangbobozhu/photo/main/photo.json', function (data) {
                // 遍历photo数组
                $.each(data.photo, function (index, item) {
                    // 去除URL前后空格,避免加载失败
                    const imgUrl = item.url.trim();
                    // 用模板字符串正确拼接DOM
                    $("#img").append(`<a href="${imgUrl}" title="${item.name}"><img src="${imgUrl}" /></a>`);
                });

                // 所有图片添加完成后,初始化Justified Gallery
                $('#img').justifiedGallery({
                    rowHeight: 120,
                    margins: 4,
                    randomize: true
                }).on('jg.complete', function () {
                    // 绑定Colorbox预览事件
                    $(this).find('a').colorbox({
                        maxWidth: '80%',
                        maxHeight: '80%',
                        opacity: 0.8,
                        transition: 'elastic',
                        current: ''
                    });
                });
            });
        });
    </script>
</body>
</html>

关键说明:

  1. 必须先引入jQuery、Justified Gallery、Colorbox的CSS和JS资源,否则插件无法正常工作
  2. 遍历data.photo数组获取每张图片的信息,使用trim()处理URL的前后空格
  3. 模板字符串中用${变量名}的方式正确引用JavaScript变量
  4. 等待所有图片DOM元素添加完成后,再执行Justified Gallery的初始化逻辑,确保插件能一次性渲染所有图片

内容的提问来源于stack exchange,提问作者verkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:24:20