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

如何在HTML中渲染JavaScript对象中的SVG图标?

如何正确渲染存储在JavaScript对象中的SVG图标?

你的问题在于直接在HTML中写{icons.add}会被浏览器当作纯文本解析,而非HTML代码,同时你的SVG字符串是HTML转义后的格式(包含<、"这类转义字符),需要通过以下方式处理:

原生JavaScript解决方案

  1. 给目标HTML元素添加唯一标识,方便JS获取:
<span id="add-icon"></span>
<span id="remove-icon"></span>
  1. 使用JavaScript将SVG字符串赋值给元素的innerHTML属性(浏览器会自动解析转义字符并渲染SVG):
// 获取元素并设置内容
document.getElementById('add-icon').innerHTML = icons.add;
document.getElementById('remove-icon').innerHTML = icons.remove;

前端框架场景(可选)

如果你使用Vue/React这类框架,需要用框架提供的HTML渲染指令:

  • Vue:使用v-html指令替代插值语法
<span v-html="icons.add"></span>
<span v-html="icons.remove"></span>
  • React:使用dangerouslySetInnerHTML属性
<span dangerouslySetInnerHTML={{ __html: icons.add }}></span>
<span dangerouslySetInnerHTML={{ __html: icons.remove }}></span>

优化建议

你可以直接在icons对象中存储未转义的SVG字符串,提升代码可读性,效果完全一致:

const icons = {
    // Icon for the "Add to cart" button
    add: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
    // Icon for the "Remove from cart" button
    remove: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
    // Icon for the "Remove all from cart" button
    removeAll: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:55:47