如何优化lightGallery初始化代码,无需每次新增序号就编写新调用语句
JavaScript代码优化方案
优化核心逻辑是抽离重复的公共配置,通过批量匹配元素的方式统一初始化,后续新增元素无需单独写初始化调用,有两种常用实现方案:
方案1:HTML加标识属性,全程无需修改JS(推荐)
- 给所有需要初始化lightGallery的元素新增统一类名
light-gallery-item,同时通过自定义属性data-download配置每个元素对应的下载开关值:
<!-- 示例HTML结构 --> <div id="web1" class="light-gallery-item" data-download="false">...</div> <div id="web2" class="light-gallery-item" data-download="true">...</div> <div id="web3" class="light-gallery-item" data-download="true">...</div> <!-- 新增元素只要加对应类和属性即可,不用改JS --> <div id="web4" class="light-gallery-item" data-download="true">...</div>
- JS批量初始化代码:
// 抽离所有元素通用的公共配置 const commonLightGalleryConfig = { selector: 'this', mobileSettings: { controls: false, showCloseIcon: true } } // 遍历所有匹配元素自动初始化 document.querySelectorAll('.light-gallery-item').forEach(el => { const enableDownload = el.dataset.download === 'true' lightGallery(el, { ...commonLightGalleryConfig, mobileSettings: { ...commonLightGalleryConfig.mobileSettings, download: enableDownload } }) })
方案2:无需修改HTML,新增元素只需加一行配置
如果不方便修改原有HTML结构,可以直接匹配id前缀为web的元素,提前配置每个id对应的下载参数:
const commonLightGalleryConfig = { selector: 'this', mobileSettings: { controls: false, showCloseIcon: true } } // 新增元素只要在这里加对应id的download配置即可 const downloadConfigMap = { web1: false, web2: true, web3: true } // 批量匹配所有id以web开头的元素初始化 document.querySelectorAll('[id^="web"]').forEach(el => { lightGallery(el, { ...commonLightGalleryConfig, mobileSettings: { ...commonLightGalleryConfig.mobileSettings, // 未配置的id默认开启下载,可自行调整默认值 download: downloadConfigMap[el.id] ?? true } }) })
内容的提问来源于stack exchange,提问作者mrOwl
相关产品推荐
相关产品推荐

