reactjs - 在我使用 axios 做出反应的其余 Web 服务请求中,响应 json 包含 html div 元素。我怎样才能得到这个元素的值?
问题描述
[
{
"title":"Palmeiras - Coritiba",
"embed":"<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>",
"url":"https://www.some.com/coritiba-vs-palmeiras-live-stream/",
"thumbnail":"https://www.somestream.com/og/m/og934437.jpeg",
"date":"2020-10-14T21:00:00+0000",
"side1":{
"name":"Palmeiras",
"url":"https://www.some.com/live-stream/palmeiras/"
},
"side2":{
"name":"Coritiba",
"url":"https://www.some.com/live-stream/coritiba/"
}
}
]
我想从此响应中获取标题、缩略图和视频、日期字段,但无法获取视频,因为它位于 div 元素中。
解决方案
您需要使用DOMParser将 HTML 字符串读入 JavaScript 文档。您可以在其上使用 DOM 方法,例如 querySelector 和 getElementById。
这是一个从 HTML 嵌入字符串返回视频 src 的函数。
const getEmbedSrc = (embed) => {
const parser = new DOMParser();
const doc = parser.parseFromString(embed, "text/html");
return doc.getElementsByTagName('iframe')[0].src;
}
const embed = "<div style='width:100%;height:0px;position:relative;padding-bottom:calc(56.25% + 335px);' class='_scorebatEmbeddedPlayerW_'><iframe src='https://www.somestream.com/embed/g/934437/?s=2' frameborder='0' width='560' height='650' allowfullscreen allow='autoplay; fullscreen' style='width:100%;height:100%;position:absolute;left:0px;top:0px;overflow:hidden;' class='_scorebatEmbeddedPlayer_'></iframe></div>";
console.log(getEmbedSrc(embed));
或者,您可以使用正则表达式查找匹配项。
推荐阅读
- ionic-framework - Ionic 4 滚动时隐藏工具栏
- scala - Any和_有什么区别
- android - 某些手机中未显示 Toast 通知
- python - 多重继承:第二个基类构造函数要求泄漏到第一个基类构造函数
- jquery - Jquery滚动减少div的比例
- ruby-on-rails - Ruby on Rails 路由部署问题
- mysql - 如何在 sequelize 上创建存储过程
- java - 如何使用 Netty Reactor 关闭 TcpClient 连接?
- c# - 条码 ASP.NET C# 问题
- html - 在 PhpStorm 中选择标签。我想在 PhpStorm 中打开标签,关闭它并将选择器放在中间(就像在 Sublime 中一样)