For example, when I want to use ajax to insert an li into a list, I will directly splice the data and html tags into a complete html sentence, and then insert it into the ul. Whether the data is retrieved from the server or from user input - it's the same either way.
This splicing process is very inelegant when placed in a JavaScript file. If you also put style in JavaScript, then the data, structure, and style are all in one pot. Maintaining such code will make people want to commit suicide. The most egregious thing is to put all the HTML that will be generated on the page directly on the server side. The data spit out by Ajax contains the
tag. Such a page has almost no scalability. Modifying a front-end style requires back-end code. modification.
Later we learned that instead of customizing the style of the DOM in JavaScript, we only need to define the corresponding class in the CSS file, and then use this class in JavaScript.
The next thing we have to do is use JavaScript templates to separate the HTML structure (in this case, the tag) from the JavaScript as well.
There are many JavaScript templates on the market. Take the excellent template handlebars as an example:
We define the template in the html of the page:
Then in our logical JavaScript code we can put Data is spliced into this template:
var source = $ ("#list-template").html(); //The template source is usually placed in the html script. Here we use jQuery, or you can use other methods to directly obtain the content string
var template = Handlerbars.compile (source); //Compile and generate a template template
var context = {title:"This is a todo item"} //Get data, the data is usually obtained from ajax or input
var html = template(context ); //Data template = new html
This is the basic usage. For more logic, please refer to the official documentation: http://handlebarsjs.com/Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn