[英]html page to json object
I want to append html page to json object, and want to access the div tags by there id from json object. 我想将html页面附加到json对象,并希望通过json对象中的id访问div标签。 I am new to this and don't know want to do.
我是新手,不知道想做什么。
the scenario is like this: 场景是这样的:
I have a html page in which multiple div tags are there with id=page1, page 2 and so on. 我有一个html页面,其中有多个div标签,其中id = page1,第2页,依此类推。 I want to add this page to json object and than access it page id wise in js ie page1 page2 and so on..can anyone provide some solution to this.
我想将此页面添加到json对象,而不是在js即page1 page2中访问它的页面,依此类推。可以为任何人提供一些解决方案。
I have just seen some values are entered in json object.how to append some html page or the elements to it? 我刚刚看到在json object.how中输入了一些值来附加一些html页面或元素吗?
If I read you correctly, you are trying to store page contents in a JSON object for future use. 如果我正确地读了你,你试图将页面内容存储在JSON对象中以备将来使用。
Saving page content is straight forward, get the innerHTML
of the body
tag into a variable or assign directly to your JSON object's property. 保存页面内容是直截了当的,将
body
标签的innerHTML
转换为变量或直接分配给JSON对象的属性。
var body = [].slice.call(document.getElementsByTagName('body'))[0];
json.Content = body.innerHTML;
Getting the JSON object's property to be able to query, is a little tricky. 让JSON对象的属性能够查询,有点棘手。 You will need to use the DOM parser to parse it and then query it.
您将需要使用DOM解析器来解析它,然后查询它。
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(json.Content, "text/html");
Here is a small demo: 这是一个小型演示:
var data = '{"id":"1", "Title":"Page", "Content":""}'; var json = JSON.parse(data); var body = [].slice.call(document.getElementsByTagName('body'))[0]; json.Content = body.innerHTML; var parser = new DOMParser(); var htmlDoc = parser.parseFromString(json.Content, "text/html"); console.log(htmlDoc.getElementById("Page-02").innerText);
<div id="Page-01"> 1. Lorem ipsum dolor sit amet, consectetur adipiscing elit </div> <div id="Page-02"> 2. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua </div> <div id="Page-03"> 3. Ut enim ad minim veniam </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.