我有两个 HTML 页面。
索引.html
<div id="source">
Contenido de Usuario
</div>
<input type="button" id="export" value="Export Data">
Users.html
<div id="target">
</div>
如何使用 JavaScript 在
Users.html中的目标
<div>
元素内显示 Index.html中源
<div>
元素的内容?
fetch()
API。
索引.html
<div id="source">
Contenido de Usuario
</div>
Users.html
<div id="target">
<!-- content will be inserted here -->
</div>
<script>
window.onload = function() {
fetch("Index.html")
.then(response => {
if (!response.ok) {
throw new Error("Error with response.");
}
return response.text();
})
.then(html => {
let parser = new DOMParser();
let doc = parser.parseFromString(html, "text/html");
let sourceContent = doc.getElementById("source").textContent;
document.getElementById("target").textContent = sourceContent;
})
.catch(error => {
console.error("Error fetching content:", error);
});
};
</script>
您可能还需要首先清理 HTML 内容,只是为了确保使用 DOMPurify 进行附加是安全的。
您没有提及该来源的大小或数据的种类......这两者对于做出明智的决定都非常重要。
无论如何,假设大小小于 2.5MB 并且数据是纯文本,里面没有什么特别的,我想你可以......
在 Index.html
<body onload="sessionStorage.setItem('source',source.textContent);">
在 Users.html
<body onload="target.textContent=sessionStorage.getItem('source');">
NB:未经测试的伪代码建议。