如何将基于ID的重复Lightbox JS代码优化为可扩展动态实现
优化Lightbox动态适配多元素实现
核心优化思路
利用按钮的data-ref属性与对应模板的id建立关联,通过遍历所有按钮动态创建Lightbox实例并绑定点击事件,彻底消除硬编码重复代码,支持任意数量的模板元素。
优化后的代码
HTML(保持原有结构不变)
<template id="one"> <h1>HTML <template one> Tag</h1> <p>The template element holds HTML code without displaying it.<br>Doesn't work in older browsers.</p> </template> <button class="template" data-ref="one">template</button> <template id="two"> <h1>HTML <template two> Tag</h1> <p>The template element holds HTML code without displaying it.<br>Doesn't work in older browsers.</p> </template> <button class="template" data-ref="two">template two</button>
JavaScript(动态实现版本)
// 获取所有模板按钮 const templateButtons = document.querySelectorAll('button.template'); // 遍历按钮,动态绑定事件 templateButtons.forEach(button => { // 通过data-ref获取对应模板的ID const templateId = button.dataset.ref; // 找到对应的模板元素 const templateElement = document.getElementById(templateId); // 创建Lightbox实例并绑定点击事件 const lightboxInstance = basicLightbox.create(templateElement); button.onclick = lightboxInstance.show; });
额外优化:缓存实例(避免重复创建)
如果按钮会被多次点击,可以提前缓存所有Lightbox实例,提升性能:
// 缓存所有模板对应的Lightbox实例 const lightboxInstances = {}; // 预创建所有实例 document.querySelectorAll('template').forEach(template => { lightboxInstances[template.id] = basicLightbox.create(template); }); // 绑定按钮事件 document.querySelectorAll('button.template').forEach(button => { button.onclick = () => lightboxInstances[button.dataset.ref].show(); });
优势说明
- 无需手动编写每个元素的实例创建和事件绑定代码
- 新增模板和按钮时,只需保证
data-ref与模板id一致,无需修改JS - 代码简洁可维护,适配任意数量的元素
内容的提问来源于stack exchange,提问作者Joshua Schmitz
相关产品推荐
相关产品推荐

