javascript - 如何使用双引号删除访问 JS 对象属性
问题描述
我从 URL 获取数据。并且数据看起来像下面的代码。如何访问图像源和内容?(请注意,当我 console.log data.description 时,它控制台未定义)。
data:{
title: "title of the data"
description:"<div class="feed-description"><p style="text-align: center;"><img alt="" src="http://....jpg" style="width: 600px; height: 350px;" /></p><p><government's financial crisis?</p><p>Working out us realling good for your body(<em>depass</em>).</p><p>Finance Ministry insider disclosed that the annual <em>depass</em> at the State House cost.</p></div>"
}
解决方案
假设响应是作为常数获得的:
const data = {
title: "title of the data",
description:`<div class="feed-description"><p style="text-align: center;"><img alt="" src="http://....jpg" style="width: 600px; height: 350px;" /></p><p><government's financial crisis?</p><p>Working out us realling good for your body(<em>depass</em>).</p><p>Finance Ministry insider disclosed that the annual <em>depass</em> at the State House cost.</p></div>`
}
如果您想访问描述 HTML 字符串的内容,您需要解析该字符串,创建一个虚拟 DOM 元素并将该字符串添加到其中。然后你可以像操作任何 DOM 元素一样操作它。
例子:
const el = document.createElement('div');
el.innerHTML = data.description;
// Getting the image source
const img = el.getElementsByTagName('img')[0]; // matching the first position
const source = img.src;
// Getting the div content
const divContent = el.getElementsByTagName('div')[0]
推荐阅读
- python - 如何通过Python中MCU发送的串口读取字节
- json - 在 JOLT 中将数组值映射到 JSON
- android - 更改设备方向后如何保存 ArrayList 数据并在 AutoCompleteTextView 中使用
- python - 蓝牙 - 在 linux 中检查 rssi
- redis - 将 Redis DEL 转换为 UNLINK 命令
- c - 尝试将字符串直接传递给函数时会导致分段错误
- angular - 使用 forkJoin 运行嵌套的 http 请求
- html - 应用了哪个 CSS 属性?
- scala - 为什么 cat 的效果异步签名使用 Either[Throwable, A] 而不是 Try[A]?
- android - 从 secp256r1 曲线中获取 x 和 y