【发布时间】:2018-10-07 20:42:45
【问题描述】:
我有一个 HTML 模板,其中包含一个 DIV(包含一个按钮)和一个脚本,该脚本将包含一个在单击该按钮时调用的函数(通过 $.get() 检索到 var text 的 template.html):
<div id="CLC_Form">
various text and checkbox inputs go here...
<br>
<input type="button" id="close_clc" value="Done" onclick="CLC_Done()" />
</div>
<script>
function CLC_Done() {
document.getElementById("CLC_Form").style.display = "none";
}
</script>
但是在.get callback() 中,我不能将appendChild(text) 这个HTML 内容传递给BODY,因为它是一个字符串,而不是一个实际的HTML 元素。
我可以createElement('div') 和createElement("script"),并从模板中为每个模板插入innerHTML,但是我的模板必须只有div 和脚本的innerHTML,没有它们的div 和script 标签,这使得模板代码不清楚它是什么。它看起来就像“松散的代码”,我必须有两个单独的模板才能做到这一点。
我要插入的页面如下所示(之前的 index.html):
<body>
<div style="padding:20px;">
<div style="clear:both; margin-bottom:32px;">
Some stuff
</div>
<div id="aPanels"></div>
<div id="bPanels"></div>
<div id="cPanels"></div>
</div>
</body>
而我想要达到的最终结果是这样的(index.html 之后):
<body>
<div style="padding:20px;">
<div style="clear:both; margin-bottom:32px;">
Some stuff
</div>
<div id="aPanels"></div>
<div id="bPanels"></div>
<div id="cPanels"></div>
<div id="CLC_Form">
various text and checkbox inputs go here...
<br>
<input type="button" id="close_clc" value="Done" onclick="CLC_Done()" />
</div>
<script>
function CLC_Done() {
document.getElementById("CLC_Form").style.display = "none";
}
</script>
</div>
</body>
有没有办法做到这一点?还是我必须 createElement() 并从两个单独的模板中设置.innerHTML?
如果需要,我可以使用 jQuery,但更喜欢 vanilla js。
【问题讨论】:
标签: javascript jquery html