我在localStorage中存储了一串html代码,我想要将该字符串转换为文档并将该文档添加到现有页面。到目前为止,我想到了:
var data = localStorage.getItem("data");
var frag = document.createRange().createContextualFragment(data);
document.body.appendChild(frag);
但是在页面中,文档片段只是一个简单的字符串。
编辑
我目前有html:
<html>
<head>
</head>
<body>
</body>
</html>
我出于测试目的保存到本地存储的字符串是 <p>Test</p>
我试图得到的结果:
<html>
<head>
</head>
<body>
<p>Test</p>
</body>
</html>
我得到的结果是:
<html>
<head>
</head>
<body>
"<p>Test</p>"
</body>
</html>
如果本地存储中的文本是HTML,则可以使用将其插入到任何其他现有元素的开头,结尾,之前或之后insertAdjacentHTML
。例如,要使用html
末尾的文档正文中的HTML添加到文档中:
document.body.insertAdjacentHTML("beforeend", html);
例:
const html = "<p>This is a new paragraph with <em>emphasized</em> text.</p>";
document.body.insertAdjacentHTML("beforeend", html);
<p>This paragraph is already on the page.</p>
innerHTML
如果要完全删除该元素的当前内容并将其替换为HTML字符串中定义的内容,则也可以使用现有元素的属性:
someElement.innerHTML = html;
例:
const html = "This is the new content for the paragraph, with <em>emphasized</em> text.";
document.getElementById("existing-paragraph").innerHTML = html;
<p id="existing-paragraph">This paragraph is already on the page.</p>
如果不是HTML,则可以将其放在一个元素(例如ap
或div
)中,然后通过appendChild
或将其附加到某个位置insertBefore
,例如:
const p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
例:
const text = "This is plain text, so things like <this> don't get misinterpreted as HTML.";
const p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
或者只是使用createTextNode
以下命令将其附加为原始文本:
const textNode = document.createTextNode(text);
document.body.appendChild(textNode);
例:
const text = "This is plain text, so things like <this> don't get misinterpreted as HTML.";
const textNode = document.createTextNode(text);
document.body.appendChild(textNode);
在评论中,我们发现本地存储中的文本已经过HTML编码,如下所示:
<p>Testing <em> one two three</em></p>
这意味着无论将文本放在本地存储中的代码是什么,然后再进行编码(因为本地存储不这样做;它会忠实地存储并返回您提供的确切字符串)。最好的解决方案可能是更新该代码,以便它不会那样做。
如果您无法更新该代码,则可以将该文本解释为HTML,只需执行两次:一次解释<
,以此类推<
,然后再次插入并解析结果HTML。最简单的方法是创建一个元素(div
例如a),设置其元素innerHTML
,然后读取其元素textContent
。这是一个例子:
例:
const textFromLocalStorage = "<p>Testing <em> one two three</em></p>";
const div = document.createElement("div");
div.innerHTML = textFromLocalStorage;
const decodedHtml = div.textContent;
document.body.insertAdjacentHTML("beforeend", decodedHtml);
<p>This paragraph is already on the page.</p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句