我正在将一些子节点保存为 Base64。这是为了更容易地传递一组元素(节点),最终将 base64 字符串保存到数据库中,并希望将其读回原始 HTML 元素(节点)
我正在使用 atob()
和 btoa()
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
我无法重新使用这个 base64,因为我不知道如何。我知道如何将其转换回 HTML。
在我的应用程序中,当用户保存(单击按钮)时,它会使用 btoa
保存 HTML 元素(和子元素),然后我得到看起来“有趣”的字符串。
现在,我需要将其从字符串重新加载到 HTML 可以理解的内容中,以便在 GUI 中显示它。
我使用 atob(myString)
并得到一个 HTMLDivElement
我不知道如何使用这个。这意味着以下失败
我的努力是(这可能在 IE 中不起作用,但这很好)
const wrapperEle = document.getElementById("wrapper");
const destinationEle = document.getElementById("destination");
const btn = document.getElementById("button");
btn.addEventListener("click", performLogic);
function performLogic() {
destinationEle.innerHTML = null;
const myString = btoa(wrapperEle); //encode
const data = atob(myString); //decode
try {
const node = document.createElement(data);
destination.appendChild(node);
} catch (e){
alert("Failed on first effort");
}
try {
destination.append(data); //appends [object HTMLDivElement]
alert("second attempt complete");
} catch (e){
alert("Failed on second effort");
}
try {
destination = data; //appends [object HTMLDivELement]
alert("third attempt complete but nothing shows");
} catch (e){
alert("Failed on third effort");
}
try {
destination.append(myString); //appends [object HTMLDivELement]
alert("fourth attempt complete but nothing shows");
} catch (e){
alert("Failed on fourth effort");
}
}
<div id="wrapper">
<table>
<tr>
<td>data 01</td>
<td>data 02</td>
</tr>
</table>
</div>
<input type="button" id="button" value="Click" />
<div id="destination">
I want and expect this line of text to be replaced with the table content above after you click on the button
</div>
如何重新获取已编码和解码的值?理想情况下,没有 JQuery 或任何框架,只有 Javascript
我也添加了 JS,但它在 IE 中不起作用(这很好)。
最佳答案
您正在尝试选择、编码、解码,然后附加 Element
对于您想要实现的目标来说,这比必要的要复杂一些。相反,只需通过 outerHTML
获取您想要“复制”的元素的 HTML属性,然后编码、解码并替换目标 div
的 HTML。
例如:
const wrapper = document.getElementById('wrapper');
const destination = document.getElementById('destination');
const button = document.getElementById('button');
const encodeDecodeAppend = () => {
const encoded = btoa(wrapper.outerHTML); //encoded HTML
const decoded = atob(encoded); // decoded HTML
destination.innerHTML = decoded;
};
button.addEventListener('click', encodeDecodeAppend);
<div id="wrapper">
<table>
<tr>
<td>data 01</td>
<td>data 02</td>
</tr>
</table>
</div>
<input type="button" id="button" value="Click">
<div id="destination">
I want and expect this line of text to be replaced with the table content above after you click on the button
</div>
关于javascript - 如何使用 Base64 编码 HTMLTableSectionElement 并附加解码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53196531/