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

如何为JavaScript动态创建的img元素添加带_blank和nofollow的跳转链接

问题原因

  • <img> 元素本身不支持跳转能力,href 是超链接标签 <a> 的专属属性,为 <img> 添加 href 属性不会被浏览器识别为跳转规则,因此无法实现点击跳转效果。

正确实现方案

需要先创建 <a> 标签作为图片的外层容器,将跳转相关属性配置在 <a> 标签上,再把 <img> 元素插入到 <a> 标签内即可,完整实现代码如下:

// 创建跳转用的a标签,配置跳转属性
const link = document.createElement('a');
link.href = mylinkVariable; // 替换为你的跳转链接变量/值
link.target = '_blank';
link.rel = 'nofollow';

// 原有创建图片的逻辑保持不变
const image = document.createElement('img');
image.setAttribute('class', 'imgGame');
image.setAttribute('alt', game.name );
image.setAttribute('title', game.name );
image.src = game.background_image;

// 嵌套元素后插入到父容器
link.appendChild(image);
card.appendChild(link);

内容的提问来源于stack exchange,提问作者sama BARI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:54:02