通过 vanilla javascript 生成 HTML 标签

Generating HTML tags through vanilla javascript

本文关键字:HTML 标签 生成 javascript vanilla 通过      更新时间:2023-09-26

一些网站使用以下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标签是通过vanilla JavaScript生成的,不使用任何库。此代码是由程序员生成或编写的吗?什么样的方法使用这种生成HTML的风格?

我也不知道顺便说一下,确定这些是否可能。

你不应该使用 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>"


方法2:

此方法涉及使用各种 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...


方法3:

使用此方法,我们使用模板系统,例如车把(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);

希望这有帮助,请随时问我您的任何问题。