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

标签 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 主包装器中添加示例测试,但此行不起作用。

最佳答案

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

关于javascript - 如何将 HTML 中的 Replace {{content}} 占位符替换为存储在本地存储中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064115/

相关文章:

javascript - Outlook Mac App 身份验证 token 不匹配

javascript - 如何将异步调用返回的Json数据正确绑定(bind)到knockout observableArray

jquery - 模仿打开/关闭抽屉的滑动/动画行为

javascript - 按名称的一部分查找数据属性

javascript - 如何在 JavaScript 中将转义的 unicode 转换为表情符号?

javascript - 如何通过 onclick 检查 jQuery 将日期时间值添加到输入

javascript - Ajax成功函数未接收数据

html - 将 h2 标签的文本垂直居中与背景对齐

java - Rad 上传 Java 小程序和 z-index

javascript - 滑动横幅 90% HTML+CSS3 10% JS