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

如何在img标签的src属性中使用对象?

如何在HTML img标签的src属性中使用对象属性

你当前的写法 <img src="item.img"> 会被浏览器直接解析为字符串路径 "item.img",而非读取对象item的img属性值。以下是不同场景下的正确实现方式:

1. 原生JavaScript动态赋值

通过JS获取DOM元素后,直接将对象属性值赋值给src:

<img id="targetImg" alt="示例图片">

<script>
// 定义包含图片路径的对象
const item = {
  img: "https://i.sstatic.net/m8PDy.png"
};

// 绑定对象属性到img的src
const imgEl = document.getElementById('targetImg');
imgEl.src = item.img;
</script>

2. Vue框架中绑定

使用v-bind指令(简写为:)绑定对象属性:

<template>
  <img :src="item.img" alt="示例图片">
</template>

<script setup>
const item = {
  img: "https://i.sstatic.net/m8PDy.png"
};
</script>

3. React框架中绑定

用大括号包裹表达式,直接引用对象属性:

import React from 'react';

const App = () => {
  const item = {
    img: "https://i.sstatic.net/m8PDy.png"
  };
  return <img src={item.img} alt="示例图片" />;
};

export default App;

示例效果:
示例图片

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:45:41