【问题标题】:How do I remove access JS object properties with double quotation如何使用双引号删除访问 JS 对象属性
【发布时间】:2018-09-15 02:42:10
【问题描述】:

我从 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>"
}

【问题讨论】:

  • 您确定这是实际响应吗?如果是这样,您应该修复损坏的 API,以便它返回正确的可解析 JSON。
  • 是的,这就是我得到的回复。它已获取 rss 提要 URL(一个网站)。
  • 假设data实际上是一个真实的对象,你可以试试console.log(JSON.stringify(data))。 JS 对象的控制台表示不能很好地转换为复制/粘贴文本
  • 即使在使用 'JSON.stringify(data)' 我也只能控制 'data' 而不是 'data.discription'

标签: javascript json xml object


【解决方案1】:

假设得到的响应是一个常数:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-11
    • 2015-07-15
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多