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

如何在Observable Notebook单元格中正确嵌入多张图片?

在Observable Notebook中实现下拉切换图片的正确方法

问题根源

你遇到的反引号问题,是因为直接在HTML单元格中用普通字符串拼接异步URL时,Observable会将表达式的结果以带反引号的形式转义输出,导致src属性无效。正确的做法是使用Observable内置的html标签模板字面量来构建HTML内容,它能正确处理异步值和表达式注入。

实现步骤

1. 定义图片列表

先整理需要切换的图片信息,方便后续绑定下拉选项:

const images = [
  { name: "Side", label: "侧面图" },
  { name: "Front", label: "正面图" },
  // 添加更多图片项
];

2. 创建下拉选择器

用viewof绑定下拉控件,让用户可以选择要显示的图片:

viewof selectedImage = html`<select>
  ${images.map(img => html`<option value=${img.name}>${img.label}</option>`)}
</select>`

3. 动态渲染选中的图片

使用html标签模板字面量构建<img>标签,直接注入异步获取的URL,不会产生反引号问题:

html`<img 
  src=${await FileAttachment(`${selectedImage}.PNG`).url()} 
  alt=${selectedImage} 
  style="max-width: 100%;"
>`

优化方案:预加载图片URL

如果图片较多,建议提前一次性加载所有图片的URL,避免每次切换都重新请求:

// 预加载所有图片URL并存储为对象
const imageUrls = Object.fromEntries(
  await Promise.all(images.map(async img => [img.name, await FileAttachment(`${img.name}.PNG`).url()]))
);

// 渲染图片时直接使用预加载的URL
html`<img 
  src=${imageUrls[selectedImage]} 
  alt=${selectedImage} 
  style="max-width: 100%;"
>`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:25:16