[英]Generating HTML tags through vanilla javascript
某些网站使用以下JavaScript行来构建网站:
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的样式?
我也不知道是否有可能确定这些。
您不应该使用document.write
。 您会在网上找到大量建议反对它的文章,以及推荐原因。 在这里,我将向您展示3种通过JavaScript生成HTML的方法,而我个人将使用这三种方法。
此方法很简单并且效果很好,但是当必须在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>
关于在JS中使用HTML
var div = document.createElement('div');
div.setAttribute('id', 'mydiv');
document.body.appendChild(div);
这将创建一个div,为其指定ID并将其附加到正文中。 这是在JS中使用html的更可靠的方法。 您还可以加载(或预加载)和图像,例如:
var img = new Image();
img.src = "path to my file";
document.body.appendChild(img);
希望对您有所帮助,请随时问我任何问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.