使用jQuery为每个链接添加预览时重复追加多个DIV如何解决
问题核心原因
你在遍历链接的逻辑中,使用$('#value a')选中了.Post-body容器下所有的链接元素,调用append方法时自然会给所有链接都追加当前获取到的预览内容,同时给.Post-body设置id的操作属于冗余逻辑,完全不需要。
修复方案
直接针对each遍历中当前的单个链接元素做操作即可,同时可以提前过滤不需要生成预览的链接,避免发起无效请求,修改后代码如下:
this.$(".Post-body").find('a').each((i, e) => { const isMobile = navigator.userAgentData.mobile; let controller = new AbortController(); let href = e.getAttribute("href"); // 提前过滤不需要生成预览的链接,避免无效请求 if (isMobile === true || !e.text.startsWith("http")) return; fetch(`https://preview-api.bbspace.top/?url=` + encodeURIComponent(href), { method: "GET", mode: "cors", signal: controller.signal, credentials: "omit" }) .then((res) => res.json()) .then((response) => { let imgResp = '<img class="screenImg" src="' + response.image + '" width="250">'; if (response.image === undefined) { imgResp = '<img class="screenImg" src="https://www.studioippocrate.com/wp-content/uploads/2017/11/pac-404.png" width="250">'; } // 只给当前遍历到的单个a标签追加预览内容 this.$(e).append('<div class="dropdown-prev">\n' + ' <button class="dropbtn"><i class="fas fa-search"></i></button>\n' + ' <div class="dropdown-content-prev">\n' + ' <div class="donContainer">\n' + ' ' + imgResp + '' + ' <div class="titleDesc">' + response.description + '</div> ' + ' </div>\n' + ' </div>\n' + '</div>'); }) .catch(err => { // 接口请求失败的兜底处理 console.log('预览获取失败', href, err) }); });
关键修改点
- 移除了给
.Post-body设置id的冗余代码 - 将预览内容的追加目标从所有链接改为当前遍历到的单个链接
this.$(e) - 将无效链接的判断逻辑移到fetch请求前,减少不必要的接口请求
- 新增了请求异常捕获逻辑,避免接口报错影响页面正常运行
内容的提问来源于stack exchange,提问作者juniorDevFla
相关产品推荐
相关产品推荐

