【问题标题】:Generating HTML tags through vanilla javascript通过 vanilla javascript 生成 HTML 标签
【发布时间】:2015-01-16 21:34:32
【问题描述】:

一些网站使用以下 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 是不好的做法,您的代码中的 HTML 字符串也是如此。查看 DOM。
  • 不幸的是,无法分辨。一些脚本会生成这种类型的代码,但也没有什么能阻止开发人员手动完成。最佳实践是使用 DOM 方法,例如 createElement
  • 感谢您的回答。我正在使用 angularjs 开发 Web 应用程序,只是询问它是否已生成。

标签: javascript html web


【解决方案1】:

您不应使用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>

【讨论】:

    【解决方案2】:

    关于在 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);
    

    希望对您有所帮助,如有任何问题,请随时问我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 2016-10-11
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      相关资源
      最近更新 更多