首页 > 解决方案 > 如何使用双引号删除访问 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>"
}

标签: javascriptjsonxmlobject

解决方案


假设响应是作为常数获得的:

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]

推荐阅读