如何更新src属性?JSON存储季节图片及HTML使用方法
月度模态框图片扩展实现方案
1. 在JSON数据中存储图片路径的方式
直接在原有月份数据的JSON对象里新增一个字段(比如imagePath),用来存储对应月份的图片相对/绝对路径。示例如下:
const monthData = [ { "month": 8, "title": "盛夏八月", "description": "蝉鸣阵阵,热浪席卷,是一年中最炎热的时节", "imagePath": "./assets/images/summer-august.jpg" }, { "month": 12, "title": "寒冬腊月", "description": "白雪皑皑,寒风凛冽,年末的静谧与温暖并存", "imagePath": "./assets/images/winter-december.jpg" } // 其他月份数据按需补充 ];
这种方式能让每个月份的标题、描述、图片路径形成关联,后续调用时直接取值即可。
2. 更新HTML中img元素的src属性
第一步:在模态框中添加img元素
先确保你的Bootstrap模态框里包含一个用于展示图片的img标签,给它设置唯一ID方便jQuery选择:
<div class="modal fade" id="monthModal" tabindex="-1" aria-labelledby="monthModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="monthModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <!-- 新增的图片元素 --> <img id="monthModalImg" src="" alt="月度主题图" class="img-fluid mb-3"> <p id="monthModalDesc"></p> </div> </div> </div> </div>
第二步:在jQuery点击事件中更新src属性
在原来处理按钮点击、更新文本的逻辑里,新增更新img元素src的代码:
// 假设月份按钮都有data-month属性,存储对应月份数字 $('.month-btn').click(function() { const targetMonth = parseInt($(this).data('month')); // 从JSON数据中匹配对应月份的信息 const monthInfo = monthData.find(item => item.month === targetMonth); if (monthInfo) { // 更新图片路径 $('#monthModalImg').attr('src', monthInfo.imagePath); // 同步更新alt属性,提升可访问性 $('#monthModalImg').attr('alt', `${monthInfo.title}主题图`); // 原有文本更新逻辑 $('#monthModalLabel').text(monthInfo.title); $('#monthModalDesc').text(monthInfo.description); // 打开模态框 $('#monthModal').modal('show'); } });
可选:处理图片加载失败的情况
如果担心图片路径出错导致空白,可以给img元素绑定错误事件,设置默认 fallback 图片:
$('#monthModalImg').on('error', function() { $(this).attr('src', './assets/images/default-month.jpg'); });
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

