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

时间:2017-05-19 07:35:30

标签: javascript jquery html

我有一个名为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后,我想进一步用密钥{{content}}和对象section231替换description要做到这一点,我已经编写了在div主包装中添加样本测试的代码,但这行不起作用,请帮忙。

2 个答案:

答案 0 :(得分:0)

您不需要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

答案 1 :(得分:0)

试试此代码

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

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

相关问题