我的html中有以下脚本标记,
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "VideoObject",
"name": "Title",
"description": "Video description",
"thumbnailUrl": [
"https://www.xpertdox.com/assets/images/XperDox_Cover_Art .png"
],
"uploadDate": "2015-02-05T08:00:00+08:00",
"duration": "PT1M51S",
"embedUrl": "https://www.youtube.com/watch?v=LDIYgpraBHA",
"interactionCount": "2347"
}
</script>
我想通过我的js文件将值附加到此处,例如
"name": "My Title",
"description": "My description"
但我不知道如何为脚本标签表格js分配值。我正在使用角度js.Can任何人请建议我帮助。谢谢..
答案 0 :(得分:0)
我对你的意思感到有些困惑但是已经创建了一些可能有帮助的片段。
可以使用JavaScript从json-script-tag元素获取内容,方法是使用id或查询选择器获取对它的引用。
获得引用后,可以将json-script-tag的文本解析为JavaScript对象,并像处理普通对象一样对其进行操作。
最后,您可以将修改后的JSON写回脚本元素,但我不确定在什么情况下这将是处理数据传递的合适模式。
// get a reference to the script element
var jsonScript = document.querySelector('script[type="application/ld+json"]');
// parse the json-data element into a JS object
var json = JSON.parse(jsonScript.innerHTML)
// Set the object properties as required
json["name"] = "My Title"
json["description"] = "My description"
// write out the object back to the script tag (with pretty formatting)
// check in your browser developer tools to see the modified tag
jsonScript.innerHTML = JSON.stringify(json, null, 2)
console.log('Script modified - check your developer tools to see the changes')
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "VideoObject",
"name": "Title",
"description": "Video description",
"thumbnailUrl": [
"https://www.xpertdox.com/assets/images/XperDox_Cover_Art .png"
],
"uploadDate": "2015-02-05T08:00:00+08:00",
"duration": "PT1M51S",
"embedUrl": "https://www.youtube.com/watch?v=LDIYgpraBHA",
"interactionCount": "2347"
}
</script>