如何将 HTML 中的 {{content}} 占位符替换为存储在本地存储中的文本



我有一个名为showdesign.html的页面,它只有4行代码,即:

<script>
var getData = JSON.parse(localStorage.getItem("templateType"));
document.write(getData.template_code);
console.log(getData.template_code);
$("#main-wrapper").html("content of placeholder here");
</script>

当页面加载时,它会从本地存储的键templateType和对象template_code中获取 html 结构。结构如下所示:

 <html>
    <head>
    </head>
    <body>
<div id="main-wrapper">
    {{content}}
</div>
    </body>
    </html>

执行 document.write 后,我想进一步用键section231和对象description替换{{content}}。为此,我编写了代码以在div 主包装器中添加示例测试,但这行不起作用。

你不需要jQuery来做到这一点,只需用你的存储变量的值设置innerHTML,如下所示:

// Store
localStorage.setItem("content", "<span class='myclass'>my content</span>");
document.getElementById("main-wrapper").innerHTML = localStorage.getItem("content");
.myclass {
  font-weight: bold;
}
<html>
    <head>
    </head>
    <body>
<div id="main-wrapper">
    {{content}}
</div>
    </body>
    </html>

请注意:要在 chrome 上运行上述脚本,您必须使用以下命令从命令行启动它:

chrome.exe --disable-web-security

试试这段代码

var getData = JSON.parse('{' + localStorage.getItem("templateType") + '}');

不确定,但它可能对您有用

最新更新