简体   繁体   English

如何仅使用JavaScript创建HTML代码?

[英]How do I use just JavaScript to create HTML code?

I've been trying to use pure JavaScript ( no jQuery ) to recreate HTML content within the container. 我一直在尝试使用纯JavaScript( 没有jQuery )在容器内重新创建HTML内容。 But, nothing shows up on the webpage when I run. 但是,当我运行时,网页上没有任何显示。 I did a lot of research online, but still no luck. 我在网上做了很多研究,但还是没有运气。 Could anyone help me to take a look? 有人可以帮我看看吗?

ps Sorry about my code is long and messy. ps对不起,我的代码冗长而混乱。 If you could help me point out which part of function or format I did wrong and tell me the correct way that would be great! 如果您可以帮助我指出我在功能或格式的哪一部分做错了,请告诉我正确的方法将是不错的选择! Thank you! 谢谢!

Here is the original code I am trying to duplicate: 这是我要复制的原始代码:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h3>Nothing clicked yet!</h3>
      <button type="button" class="btn btn-default btn-lg">Star</button>
      <hr>
      <div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">1</button>
          <button type="button" class="btn btn-default">2</button>
          <button type="button" class="btn btn-default">3</button>
          <button type="button" class="btn btn-default">4</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">5</button>
          <button type="button" class="btn btn-default">6</button>
          <button type="button" class="btn btn-default">7</button>
        </div>
        <div class="btn-group">
          <button type="button" class="btn btn-default">8</button>
        </div>
      </div>
      <hr>
      <div>
        <div class="btn-group btn-group-lg">
          <button type="button" class="btn btn-default">Left</button>
          <button type="button" class="btn btn-default">Middle</button>
          <button type="button" class="btn btn-default">Right</button>
        </div>
      </div>
    </div>
  </div>
</div>

Here is what I have so far: 这是我到目前为止的内容:

function myFunction() {
  var makeDiv = document.createElement('DIV');
  var makeHead = document.createElement('H3');
  var makeBTN = document.createElement('BUTTON');

  var swapH3 = function swap() {
      //locate button textNode then use it to replace the text inside of h3;
  };

  var rowDiv = document.getElementById("container").appendChild("makeDiv");
  rowDiv.className = "row";
  rowDiv.id = "row";

  var colDiv = document.getElementById('row').appendChild('makeDiv');
  colDiv.className = "col-md-12";
  colDiv.id = "col";

  var head = document.getElementById('col').appendChild('makeHead');
  head.id = "head";
  head.createTextNode('Nothing clicked Yet!');

  var btn0 = document.getElementById('col').appendChild('makeBTN');
  btn0.id = "btn0";
  btn0.className = "btn btn-default btn-lg on";
  btn0.createTextNode = ('star');
  btn0.type = "button";
  btn0.onclick = swapH3;

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng1 = document.getElementById('col').appendChild('makeDIV');
  btng1.id = 'btng1';

  document.getElementById('col').appendChild(document.createElement(HR));

  var btng2 = document.getElementById('col').appendChild('makeDIV');
  btng2.id = 'btng2';

  var btngA = document.getElementById('btng1').appendChild('makeDIV');
  btngA.id = 'btngA';
  btngA.className = 'btn-group';

  var btngB = document.getElementById('btng1').appendChild('makeDIV');
  btngB.id = 'btngB';
  btngB.className = 'btn-group';

  var btngC = document.getElementById('btng1').appendChild('makeDIV');
  btngC.id = 'btngC';
  btngC.className = 'btn-group';

  var btngD = document.getElementById('btng2').appendChild('makeDIV');
  btngD.id = 'btngD';
  btngD.className = 'btn-group btn-group-lg';

  var btn1 = document.getElementById('btngA').appendChild('makeBTN');
  btn1.className = 'btn btn-default';
  btn1.type = 'button';
  btn1.createTextNode = ('1');
  btn1.onclick = swapH3;

  var btn2 = document.getElementById('btngA').appendChild('makeBTN');
  btn2.className = 'btn btn-default';
  btn2.type = 'button';
  btn2.createTextNode = ('2');
  btn2.onclick = swapH3;

  var btn3 = document.getElementById('btngA').appendChild('makeBTN');
  btn3.className = 'btn btn-default';
  btn3.type = 'button';
  btn3.createTextNode = ('3');
  btn3.onclick = swapH3;

  var btn4 = document.getElementById('btngA').appendChild('makeBTN');
  btn4.className = 'btn btn-default';
  btn4.type = 'button';
  btn4.createTextNode = ('4');
  btn4.onclick = swapH3;

  var btn5 = document.getElementById('btngB').appendChild('makeBTN');
  btn5.className = 'btn btn-default';
  btn5.type = 'button';
  btn5.createTextNode = ('5');
  btn5.onclick = swapH3;

  var btn6 = document.getElementById('btngB').appendChild('makeBTN');
  btn6.className = 'btn btn-default';
  btn6.type = 'button';
  btn6.createTextNode = ('6');
  btn6.onclick = swapH3;

  var btn7 = document.getElementById('btngB').appendChild('makeBTN');
  btn7.className = 'btn btn-default';
  btn7.type = 'button';
  btn7.createTextNode = ('7');
  btn7.onclick = swapH3;

  var btn8 = document.getElementById('btngC').appendChild('makeBTN');
  btn8.className = 'btn btn-default';
  btn8.type = 'button';
  btn8.createTextNode = ('8');
  btn8.onclick = swapH3;

  var btnLeft = document.getElementById('btngD').appendChild('makeBTN');
  btnLeft.className = 'btn btn-default';
  btnLeft.type = 'button';
  btnLeft.createTextNode = ('Left');
  btnLeft.onclick = swapH3;

  var btnMiddle = document.getElementById('btngD').appendChild('makeBTN');
  btnMiddle.className = 'btn btn-default';
  btnMiddle.type = 'button';
  btnMiddle.createTextNode = ('Middle');
  btnMiddle.onclick = swapH3;

  var btnRight = document.getElementById('btngD').appendChild('makeBTN');
  btnRight.className = 'btn btn-default';
  btnRight.type = 'button';
  btnRight.createTextNode = ('Right');
  btnRight.onclick = swapH3;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container" id="container">
</div>

You have to call document.createElement every time want to append an element. 每次要附加一个元素时,都必须调用document.createElement Also, you are not supposed to pass a string to appendChild . 另外,您不应该将字符串传递给appendChild You are supposed to pass in what document.createElement returns. 您应该传递document.createElement返回的内容。 Also, createTextNode is a function of document , and it returns a text node that you have to append to the element yourself. 另外, createTextNodedocument的功能,它返回一个文本节点,您必须自己将该文本节点附加到元素上。 Your code should look something like: 您的代码应类似于:

  var rowDiv = document.createElement("DIV");
  document.getElementById("container").appendChild(rowDiv);
  rowDiv.className = "row";
  rowDiv.id = "row";

  var colDiv = document.createElement("DIV");
  document.getElementById("row").appendChild(colDiv);
  colDiv.className = "col-md-12";
  colDiv.id = "col";

  var head = document.createElement("H3");
  document.getElementById("col").appendChild(head);
  head.id = "head";
  head.appendChild(document.createTextNode('Nothing clicked Yet!'));

Using JavaScript to create HTML: 使用JavaScript创建HTML:

Creating HTML elements: 创建HTML元素:
Each HTML element must first be specifically created. 必须首先专门创建每个HTML 元素

There are a variety of ways to do this. 有多种方法可以做到这一点。 The most commonly used are: 最常用的是:

  • Use document.createElement() to create the element. 使用document.createElement()创建元素。
    var myDiv = document.createElement("div");
    myDiv will be a reference to the element you just created. myDiv将是您刚刚创建的元素的引用。 The element will not yet be part of the DOM. 该元素尚未成为DOM的一部分。 If you want it to be displayed, you will need to add it to the DOM. 如果要显示它,则需要将其添加到DOM。
  • Assign an HTML string to the innerHTML property of another element. 将HTML字符串分配给另一个元素的innerHTML属性。
    containingElement.innerHTML = "<div id="divA"><div id="divB">Some Text"</div></div>";
    There are a variety of potential issues with directly adding HTML text to the DOM. 直接将HTML文本添加到DOM存在多种潜在问题。 In particular, there are security issues if any part of the HTML text you are adding is not derived from strings hard coded in your program. 特别是,如果要添加的HTML文本的任何部分不是从程序中的硬编码字符串派生的,则存在安全问题。
    Depending on what you are assigning, there can be performance issues with repeatedly changing large parts of the DOM by assigning to innerHTML . 根据要分配的内容,通过分配给innerHTML反复更改DOM的大部分,可能会遇到性能问题。
  • Assign text to the textContent property of another element. 将文本分配给另一个元素的textContent属性。 This will remove any other children and create a single text node as the only child for the element. 这将删除所有其他子项,并创建一个文本节点作为该元素的唯一子项。
    elementToHaveText.textContent = "The text I want in this element."
  • Use cloneNode() to create a copy of a node, or a node and all its children. 使用cloneNode()创建节点或节点及其所有子节点的副本。
    var theCopy = nodeToCopy.cloneNode() //thecopy will be a copy of nodeToCopy.
    var theCopy = nodeToCopy.cloneNode(true) //Create a copy of nodeToCopy and all children.
  • Use insertAdjacentHTML() to create elements and insert them into the DOM using HTML text at the same time. 使用insertAdjacentHTML()创建元素,并同时使用HTML文本将它们插入DOM。 This method provides more control over inserting the elements generated from HTML text. 此方法提供了对插入从HTML文本生成的元素的更多控制。 In many/some cases it will be faster than other types of node generation and insertion. 在许多/某些情况下,它将比其他类型的节点生成和插入更快。 The HTML is inserted in relation to a reference element. HTML是相对于reference元素插入的。 You can insert the HTML, before, as children (either at the beginning or end), or after the reference element. 您可以在子元素之前(作为开始或结尾)或在reference元素之后插入HTML。
    refEl.insertAdjacentHTML('afterend',"<div id="A"><div id="B">Some Text"</div></div>"); This method has the same security concerns and assigning to innerHTML regarding direct conversion HTML text that is not hard coded in your program. refEl.insertAdjacentHTML('afterend',"<div id="A"><div id="B">Some Text"</div></div>");此方法具有相同的安全问题,并分配给innerHTML关于在程序中未进行硬编码的直接转换HTML文本。

There are additional ways to create HTML elements. 还有其他创建HTML元素的方法。 You will want to look at the documentation for documents , nodes and elements . 您将需要查看有关文档节点元素的 文档

Adding elements to the DOM : DOM添加元素:
In order for an HTML element to be visible it must be added to the DOM . 为了使HTML元素可见,必须将其添加到DOM中 There are multiple ways to add an element to the DOM. 有多种向DOM添加元素的方法。 The most commonly used are: 最常用的是:

  • Use a methodology that both creates the nodes and inserts them into the DOM at the same time. 使用既创建节点又将它们同时插入DOM的方法。 You can do so with: 您可以这样做:
    • Assign an HTML string to the innerHTML property of another element. 将HTML字符串分配给另一个元素的innerHTML属性。
    • Use insertAdjacentHTML() to create and insert elements into the DOM using HTML text. 使用insertAdjacentHTML()使用HTML文本创建元素并将其插入DOM。
  • Use appendChild() to add a child to the end of an element's list of children. 使用appendChild()将一个子代添加到元素的子代列表的末尾。
    element.appendChild(aChild);
  • Use insertBefore() to add a child to a parent prior to another child of that parent. 使用insertBefore()将一个子项添加到该父项之前,再将该子项添加到该父项。
    parentNode.insertBefore(aChild, referenceChild);
  • Use replaceChild() to replace a child of a parent node. 使用replaceChild()替换父节点的子节点。
    parentNode.replaceChild(aChild, oldChild);

As with creating elements, there are additional ways to add elements to the DOM. 与创建元素一样,还有其他方法可以将元素添加到DOM。 You will want to look at the documentation for documents , nodes and elements . 您将需要查看有关文档节点元素的 文档

You can not use the same element in the DOM multiple times. 您不能在DOM中多次使用同一元素。 If you try to do so, the element which you are trying to add in a second place will be moved from its current place in the DOM to the place where you are inserting it. 如果尝试这样做,则将要添加的第二个元素将从DOM中的当前位置移动到插入该元素的位置。 This is the normal way to move an element rather than explicitly removing it and then re-adding it in another location. 这是移动元素而不是显式删除元素然后将其重新添加到另一个位置的正常方法。

If you want to add elements which have children, you either have to create them all at one time using one of the methodologies that creates and inserts HTML text, or you need to have references to the nodes you create in order to use them when adding children later. 如果要添加包含子元素的元素,则要么必须使用创建和插入HTML文本的一种方法一次创建所有元素,要么需要引用创建的节点,以便在添加时使用它们孩子们以后。 It is significantly more efficient to have a variable which is a reference to the parent node you have created rather than having to search the DOM for that node in order to add children. 使用变量作为对您创建的父节点的引用,要比添加子节点在DOM中搜索要有效得多。

Regarding your code: 关于您的代码:

  • You are passing a string to appendChild() when you should be passing an element . 您应该在传递元素时将字符串传递给appendChild()
  • You are using document.getElementById() to try to get references to elements which you have just created. 您正在使用document.getElementById()尝试获取对刚刚创建的元素的引用。
    • None of your elements have IDs in the HTML. 您的所有元素在HTML中都没有ID。 You appear to be adding IDs just so you can use document.getElementById() to find the elements you created. 您似乎只是在添加ID,以便可以使用document.getElementById()查找创建的元素。
    • If you need a reference to an element you created, you should be keeping the reference you get from creating the element. 如果需要对创建的元素的引用,则应保留从创建元素获得的引用。 It is bad practice to perform a bunch of extra processing (searching for an element) which is completely unneeded. 坏习惯是执行一堆完全不需要的额外处理(搜索元素)。
    • You should never need to perform a call to document.getElementById() to get a reference to an element that you have created in the same function in which you need the reference. 您永远不需要执行对document.getElementById()的调用来获得对您在需要引用的同一函数中创建的元素的引用。
  • You are using createTextNode() . 您正在使用createTextNode()
    • This is a method of document , not element . 这是一种document方法,而不是element
    • For your use, setting the only child node to be a single text child node, it is more efficient to just assign to Element.textContent . 供您使用,将唯一的子节点设置为单个文本子节点,仅将其分配给Element.textContent更为有效。
  • You have created the variables makeDiv , makeHead , and makeBTN which you appear to be trying to use multiple times as a different element each time you are referring to the variable. 您已经创建了变量makeDivmakeHeadmakeBTN ,它们似乎在每次引用变量时都试图多次用作不同的元素。 It does not work the way you have coded it. 它无法按照您的编码方式工作。 As written, there is only one element of each type created. 如所写,每种类型仅创建一个元素。 You can not use the same element in multiple locations in the DOM. 您不能在DOM中的多个位置使用同一元素。
  • You have written way too much linear code. 您编写了太多的线性代码。 Your elements are very similar. 您的元素非常相似。 You should code this such that creating them is modular. 您应该对此进行编码,以使它们是模块化的。

From your question, it is unclear to me if you are attempting to create the entirety of the HTML code you have provided, or if you are trying to create everything from the <div> with class="row" and add it to the DOM within a <div> with class="container" . 从您的问题来看,我不清楚您是要创建提供的HTML代码的全部内容,还是要创建<div>带有class="row"并将其添加到DOM中在带有class="container"<div> I have assumed that you are attempting to create the entirety of the HTML. 我假设您正在尝试创建整个HTML。

I have also assumed that you want the HTML you have listed in the question without the additional attributes which are in your JavaScript. 我还假设您想要问题中列出的HTML,而没有JavaScript中的其他属性。

Here is some code that creates the HTML you are looking for: 以下是一些代码,可创建您要查找的HTML:

function createDesiredHtmlElements() {
    function createDiv(theClass) {
        var div = document.createElement("div");
        if(typeof theClass === "string") {
            div.className = theClass;
        }
        return div;
    }
    function createButton(text,theClass,type) {
        var button = document.createElement("button");
        type = (typeof type === "undefined") ? "button" : type;
        theClass = (typeof theClass === "undefined") ? "btn btn-default" : theClass;
        button.setAttribute("type",type);
        button.className = theClass;
        button.textContent = text;
        return button;
    }
    function createButtonGroupDiv(buttonsText,divClass) {
        buttonsText = (typeof buttonsText === "string") ? [buttonsText] : buttonsText;
        divClass = (typeof divClass === "undefined") ? "btn-group" : divClass;
        var div = createDiv(divClass);
        if(Array.isArray(buttonsText)) {
            buttonsText.forEach(function(buttonText) {
                div.appendChild(createButton(buttonText));
            });
        }
        return div;
    }
    //Actually create the HTML:
    var mainDiv = createDiv("container");
    var rowDiv = mainDiv.appendChild(createDiv("row"));
    var colDiv = rowDiv.appendChild(createDiv("col-md-12"));
    colDiv.appendChild(document.createElement("h3")).textContent = "Nothing clicked yet!";
    colDiv.appendChild(createButton("Star","btn btn-default btn-lg"));
    colDiv.appendChild(document.createElement("hr"));
    var midDiv = colDiv.appendChild(createDiv());
    midDiv.appendChild(createButtonGroupDiv(["1","2","3","4"]));
    midDiv.appendChild(createButtonGroupDiv(["5","6","7"]));
    midDiv.appendChild(createButtonGroupDiv("8"));
    colDiv.appendChild(document.createElement("hr"));
    var midDiv2 = colDiv.appendChild(createDiv());
    midDiv2.appendChild(createButtonGroupDiv(["Left","Middle","Right"]
                                             ,"btn-group btn-group-lg"));
    return mainDiv;
}

If you then do the following: 如果您执行以下操作:

var theDiv = createDesiredHtmlElements();
console.log(theDiv.outerHTML);

You will see the HTML: 您将看到HTML:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h3>Nothing clicked yet!</h3>
      <button class="btn btn-default btn-lg" type="button">Star</button>
      <hr>
      <div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">1</button>
          <button class="btn btn-default" type="button">2</button>
          <button class="btn btn-default" type="button">3</button>
          <button class="btn btn-default" type="button">4</button>
        </div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">5</button>
          <button class="btn btn-default" type="button">6</button>
          <button class="btn btn-default" type="button">7</button>
        </div>
        <div class="btn-group">
          <button class="btn btn-default" type="button">8</button>
        </div>
      </div>
      <hr>
      <div>
        <div class="btn-group btn-group-lg">
          <button class="btn btn-default" type="button">Left</button>
          <button class="btn btn-default" type="button">Middle</button>
          <button class="btn btn-default" type="button">Right</button>
        </div>
      </div>
    </div>
  </div>
</div>

Note that the code above does not actually put the created HTML into the DOM. 请注意,上面的代码实际上并未将创建的HTML放入DOM中。 You have not specified what you want done with the HTML once it is created. 创建HTML之后,您尚未指定要执行的操作。

There are many great template system out there. 有很多很棒的模板系统。 Personally, I like handlebarsjs , though I am sure others have excellent favorites as well. 就个人而言,我喜欢handlebarsjs ,尽管我确信其他人也很喜欢。 You should check them out. 你应该检查出来。

That aside, I find that it is sometimes easier to just build the html as text and use it rather than build the individual DOM nodes. 除此之外,我发现有时仅将html作为文本构建并使用它比构建单个DOM节点更容易。

 var html = []; html.push("<div class=\\"row\\">"); html.push("<div class=\\"col-xs-6\\">A</div>"); html.push("<div class=\\"col-xs-6\\">B</div>"); html.push("</div>"); document.getElementById("container").innerHTML = html.join(""); 
 .col-xs-6 { min-height: 3em !important; border: solid 1px; background-color: aliceblue; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div id="container" class="container"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM