如何在JavaScript中插入一大块HTML? [英] How to insert a large block of HTML in JavaScript?
本文介绍了如何在JavaScript中插入一大块HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个带有许多标签的HTML块,如何在JavaScript中插入它?
var div = document。的createElement( 'DIV');
div.setAttribute('class','post block bc2');
div.innerHTML ='这里的HTML太多了,远不止一行代码';
document.getElementById('posts')。appendChild(div);
我该怎么做对不对?
解决方案
您可以将HTML代码块保存在HTML代码中的不可见容器中(如< script>
),然后使用它 innerHTML
在JS中运行时
例如:
< document.getElementById('blockOfStuff')。innerHTML; document.getElementById('targetElement')。appendChild(div);
.red {color:red}
< script id =blockOfStufftype =text / html>这是一些随机文本。 < h1>包含HTML标记< / h1>引用也可以像一个人说的那样:这些是引号,但'这些'也是引号。< / script>< div id =targetElementclass =red>< / div> / code>
从这个答案的想法:JavaScript HERE-doc或其他大型引用机制?
If I have a block of HTML with many tags, how do insert it in JavaScript?
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code';
document.getElementById('posts').appendChild(div);
How do I do it right?
解决方案
You could keep the HTML block in an invisible container (like a <script>
) within your HTML code, then use its innerHTML
at runtime in JS
For example:
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;
document.getElementById('targetElement').appendChild(div);
.red {
color: red
}
<script id="blockOfStuff" type="text/html">
Here's some random text.
<h1>Including HTML markup</h1>
And quotes too, or as one man said, "These are quotes, but
'these' are quotes too."
</script>
<div id="targetElement" class="red"></div>
Idea from this answer: JavaScript HERE-doc or other large-quoting mechanism?
这篇关于如何在JavaScript中插入一大块HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文