您不应使用document.write。你会在网上找到大量反对它的文章以及为什么。在这里,我将向您展示通过 JavaScript 生成 HTML 的 3 种方法,我个人会使用这三种方法。
方法一:
此方法简单且效果很好,但在必须在 JS 代码中键入 HTML 时很容易出错。它还将 HTML 和 JS 混合在一起,这并不是一个好的做法。尽管如此,它仍然有效,我将这种方法用于简单的项目。
注意${some_var} 语法。我只是想出了这个,它并不特定于 JavaScript。我们将使用 JavaScript 的 replace() 方法和一个简单的正则表达式将这些占位符替换为实际值。
// A function that returns an HTML string - a.k.a. a Template
function getHtml() {
var html = '<div class="entry">';
html += '<h3 class="title">${title}</h3>';
html += '<time>';
html += '<span class="month">${month}</span> ';
html += '<span class="day">${day}</span>, ';
html += '<span class="year">${year}</span>';
html += '</time></div>';
return html;
}
// Helper function that takes an HTML string & an object to use for
// "binding" its properties to the HTML template above.
function parseTemplate(str, data) {
return str.replace(/\$\{(\w+)\}/gi, function(match, parensMatch) {
if (data[parensMatch] !== undefined) {
return data[parensMatch];
}
return match;
});
}
// Now parse the template
parseTemplate(getHtml(), {
title: 'Lorem Ipsum',
month: 'January',
day: '16',
year: '2015'
});
输出:
"<div class="something"><h3 class="title">Lorem Ipsum</h3><time><span class="month">January</span> <span class="day">16</span>, <span class="year">2015</span></time></div>"
方法二:
此方法涉及使用各种 DOM 方法,例如 document.createElement(),并且效果很好。缺点是它可能是重复的,但您始终可以使用它们创建自己的 API,就像我们使用下面的 tag() 函数一样。
// Helper function to create an element with attributes
function tag(name, attrs) {
var el = document.createElement(name.toString());
!!attrs && Object.keys(attrs).forEach(function(key) {
el.setAttribute(key, attrs[key]);
});
return el;
}
// Now create some DOM nodes
var li = tag('li', {'id': 'unique123', 'data-id': 123, 'class': 'item active'});
var p = tag('p');
// Add text to the paragraph and append it to the list item
p.textContent = 'Lorem ipsum dolor'; // Not cross-browser; more here: https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent
li.appendChild(p);
// Append the list item to the body
document.body.appendChild(li);
// Or append it somewhere else
document.getElementById('output-div').appendChild(li);
document.querySelector('.content').appendChild(li);
// Other DOM methods/props you can use include:
li.innerHTML = 'some html string';
var txt = document.createTextNode('hello');
// and more...
方法三:
通过这种方法,我们使用模板系统,例如 Handlebars (http://handlebarsjs.com/)。当您预计项目中有大量模板时,它会很好地工作。除了像下面这样的脚本标签,这些模板实际上也可以预编译成 JavaScript 函数,强烈推荐。
<!-- An HTML template made out of script tags inside your page. -->
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
现在编译模板:
// Get the HTML source
var source = document.getElementById('entry-template').innerHTML;
// Compile it - `template` here is a function similar to `getHtml()` from the first example
var template = Handlebars.compile(source);
// Provide some data to the template.
var html = template({title: "My New Post", body: "This is my first post!"});
html 变量现在包含以下内容,您可以使用 innerHTML 之类的内容将其插入您的页面:
<div class="entry">
<h1>My New Post</h1>
<div class="body">
This is my first post!
</div>
</div>