如何为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
相关产品推荐
相关产品推荐

