<title>New discoveries every day-how to add HTML code dynamically with JS</title># # #如何优雅的用js动态的添加html代码
>[Original] (Http://segmentfault.com/q/1010000000312781&sa=U&ei=r2deU9qOGM6iyAS79YHIDg&ved=0CGMQFjAK &USG=AFQJC) Thanks to Tychio for the answers.
# # #三种方案:
1. Using the DOM
???? Creating elements using CreateElement
???? Var?dialog?=?document.createelement (' div ');
???? Var?img?=?document.createelement (' img ');
???? Var?btn?=?document.createelement (' input ');
???? Var?content?=?document.createelement (' span ');
???? ? Add Class
???? Dialog.classname?=? ' Dialog ';
???? ? properties
???? Img.src?=? ' Close.gif ';
???? ? style
???? Btn.style.paddingright?=? ' 10px ';
???? ? text
???? Span.innerhtml?=? ' Do you really want GG? ‘;
???? ? put other elements in the container element
???? Dialog.appendchild (IMG);
???? Dialog.appendchild (BTN);
???? Dialog.appendchild (span);
????
> About adding class if you do not consider IE compatibility issues, you can use the Classlist method, detailed [API here] (https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). There are many other ways????? For DOM operations, in [here] (http://www.w3school.com.cn/htmldom/dom_methods.asp).
2. Using the Html5?template label
????
????
??????
????????
????????
????????
??????
????
> then you have to use the DOM operation, just don't need to create the element, then copy a copy into the body.
???? Var?dialog?=?document.queryselector (' #dialog_tpl ');
???? Dialog.content.querySelector (' img '). src?=? ' Close.gif ';
???? Dialog.content.querySelector (' span '). innerhtml?=? ' Do you really want GG? ‘;
???? Document.body.appendChild (Dialog.content.cloneNode (true));
???? The
>template tag is hidden and is used at most in the list to produce multiple copies. The detailed use method can refer to [this article] (HTTP://WWW.HTML5ROCKS.COM/EN/TUTORIALS/WEBCOMPONENTS/TEMPLATE/?REDIRECT_FROM_LOCALE=ZH). If you want to be compatible with browsers that do not support template, you can write part of the content to a compatible method and hide the template with CSS.
3. Using HTML templates
>[here] (https://developer.mozilla.org/en-US/docs/JavaScript_templates) has a variety of templates, and categorized by grammatical style. In fact, the template is much the same, is to dynamically modify the template file to make it a usable static HTML file, in fact, you can also load a portion of the HTML yourself where needed. Just use Ajax to request a modal HTML file and put the returned HTML code in the current HTML.
from for notes (Wiz)
New discoveries every day-how to gracefully Add HTML code with JS dynamically