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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:57:00