For example, when using ajax to insert a li in a list, I directly splice the data with the html tag into a complete html and insert it into ul. No matter whether the data is retrieved from the server or from the user's input-either method is the same.
This splicing process is put in a JavaScript file, which is not elegant. If you also put the style in JavaScript, the data, structure, and style are all porridge. To maintain such code, you may want to commit suicide. The most out-of-the-box way is to put all the HTML to be generated on the page directly on the server side, and the ajax spit data contains the <li> tag. Such a page has almost no scalability, modifying a foreground style involves modifying the background code.
Later we learned that we should not customize DOM styles in JavaScript, but just define the corresponding class in the CSS file and use this class in JavaScript.
Next, we need to use a JavaScript template to separate the HTML structure (in this case, the <li> tag) from JavaScript.
There are many JavaScript templates on the market. Take handlebars as an example:
We define a template in the html of the page:Copy codeThe Code is as follows: <script id = "list-template" type = "text/x-handlebars-template">
<Li >{{ title }}</li>
</Script>
Then we can splice the data in our logic JavaScript code into this template:Copy codeThe Code is as follows: var source = $ ("# list-template" ).html (); // template source, which is generally placed in the html script. Here we use jQuery, you can also use other methods to directly obtain the content string.
Var template = Handlerbars. compile (source); // compile and generate a template
Var context = {title: "This is a todo item"} // obtain data. Data is generally obtained from ajax or input.
Var html = template (context); // data + template = new html
This is the basic usage, more logic can refer to the official documentation: http://handlebarsjs.com/