Generally, two methods can be used to dynamically create elements.
1. Dom HTml
Copy codeThe Code is as follows:
Var select = document. createElement ("select ");
Select. options [0] = new Option ("add-on 1", "value1 ");
Select. options [1] = new Option ("add-on 2", "value2 ");
Select. size = "2 ";
TestDiv. appendChild (select );
});
Create the object using the createElement method of document and add it to the specified object using the appendChild method.
2. Create a JQuery Function
$ ("<Div style = \" border: solid 1px # FF0000 \ "> dynamically created div </div> ")
You can use append, appendto, prepend, and prependto to add the object to the specified object. For details, see
Http://www.jb51.net/article/35845.htm
3. It is best to create a page after the page is loaded.
You can use window. onload, but add new elements, but unfortunately the Browser executes window. the onload function is not only after the DOM tree is built, but also after all the images and other external resources are fully loaded and displayed in the browser window. therefore, if an image or other resources is loaded for a long time, visitors will see an incomplete page, even a script that depends on the dynamically added element is executed before the image is loaded, resulting in a script error.
The solution is to execute our function before the image and external resources are loaded after the DOM is parsed. Make this implementation feasible in jQuery.
Copy codeThe Code is as follows:
$ (Document). ready (
Function () {testDiv. innerHTML = "<div style = \" border: solid 1px # FF0000 \ "> Use dynamically created $ (document ). ready (function) method </div> ";}
);
Or use the simple Syntax:
Copy codeThe Code is as follows:
// JQuery uses the $ (function) Method
$ (
Function () {testDiv. innerHTML + = "<div style = \" border: solid 1px # FF0000 \ "> use the $ (function) method </div> ";}
);
Use $ () to wrap our functions. You can bind multiple functions to a page. If you use traditional window. onload, you can only call one function.
So please use this method to call the function that modifies the DOM. pay attention to document. differences between createElement and innerHTML. if possible, try to use document. createElement and $ ("<div/>") to create an object.