问题描述
某些网站使用以下JavaScript行来构建网站:
Some sites use the following JavaScript line to build the site:
document.write('<link rel="stylesheet" type="text/css" href="' + staticpath +
'resources/css/mobile-android.css" /><div class="overlay"></div>
<div class="new-folder-popup" id="message"><div class="new-folder-popup-bg"><div
class="new-folder-header">MEGA for Android</div><div class="new-folder-main-bg">
<div class="new-folder-descr">Do you want to install the latest<br/> version of the MEGA app for Android?</div><a class="new-folder-input left-b/>');
HTML标记是通过原始JavaScript生成的,无需使用任何库.此代码是由程序员生成或编写的吗?什么样的方法使用这种生成HTML的样式?
HTML tags are generated through vanilla JavaScript without using any library. Is this code generated or written by a programmer? And what kind of methods use this style of generating HTML?
我也不知道是否有可能确定这些.
I also don't know if determining these is possible by the way.
推荐答案
您不应使用 document.write
.您会在网上找到大量建议反对它的文章,以及推荐原因.在这里,我将向您展示三种通过JavaScript生成HTML的方法,而我个人将全部使用这三种方法.
You should not use document.write
. You'll find a ton of articles online recommending against it and why. Here I'll show you 3 methods to generate HTML via JavaScript, and personally I use all three of them.
此方法很简单并且效果很好,但是当必须在JS代码中键入HTML时,它很容易出错.它还将HTML和JS混合在一起,这实际上不是一个好习惯.尽管如此,它仍然有效,我将这种方法用于简单的项目.
This method is simple and works well but it can be error prone when having to type the HTML inside the JS code. Also it mixes HTML and JS together, which isn't really a good practice. Nevertheless, it works and I use this method for simple projects.
请注意 $ {some_var}
语法.我只是想出了这一点,它不是特定于JavaScript的.我们将使用JavaScript的 replace()
方法和简单的正则表达式将这些占位符替换为实际值.
Note the ${some_var}
syntax. I just came up with that and it isn't specific to JavaScript. We will replace these placeholders with actual values using JavaScript's replace()
method and a simple Regular Expression.
// 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()
,并且效果很好.缺点是它可以重复,但是您总是可以像使用下面的 tag()
函数一样,用它们创建自己的API.
This method involves using various DOM methods such as document.createElement()
and also works well. The downside is that it can be repetitive, but you can always create your own API out of them like we're doing with the tag()
function below.
// 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函数,而不是如下所示的脚本标签,因此我们强烈建议这样做.
With this method we use a Template system such as Handlebars (http://handlebarsjs.com/). It works well when you anticipate to have a lot of templates in a project. Instead of script tags like below, these templates can actually be pre-compiled into JavaScript functions too, which is highly recommended.
<!-- 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
之类的东西将其插入页面:
The html variable now contains the following and you can insert it into your page using something like innerHTML
:
<div class="entry">
<h1>My New Post</h1>
<div class="body">
This is my first post!
</div>
</div>
这篇关于通过香草javascript生成HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!