如何使用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>
关键说明:
- 必须先引入jQuery、Justified Gallery、Colorbox的CSS和JS资源,否则插件无法正常工作
- 遍历
data.photo数组获取每张图片的信息,使用trim()处理URL的前后空格 - 模板字符串中用
${变量名}的方式正确引用JavaScript变量 - 等待所有图片DOM元素添加完成后,再执行Justified Gallery的初始化逻辑,确保插件能一次性渲染所有图片
内容的提问来源于stack exchange,提问作者verkey
相关产品推荐
相关产品推荐

