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

如何优化lightGallery初始化代码,无需每次新增序号就编写新调用语句

JavaScript代码优化方案

优化核心逻辑是抽离重复的公共配置,通过批量匹配元素的方式统一初始化,后续新增元素无需单独写初始化调用,有两种常用实现方案:

方案1:HTML加标识属性,全程无需修改JS(推荐)

  1. 给所有需要初始化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>
  1. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:36:01