Home  >  Article  >  Web Front-end  >  Introduction and application of jquery’s method of dynamically creating elements_jquery

Introduction and application of jquery’s method of dynamically creating elements_jquery

WBOY
WBOYOriginal
2016-05-16 17:35:58812browse

Generally, there are two ways to dynamically create elements
1. Dom HTml

Copy code The code is as follows:

var select = document.createElement("select");
select.options[0] = new Option("Add-in1", "value1");
select.options[1] = new Option("add-in2", "value2");
select.size = "2";
testDiv.appendChild(select);
});

Create it through the createElement method of the document, and then add it to the specified object through the appendChild method

2. Create with JQuery function
$("
")
Add to the specified object through append, appendto, prepend, prependto and other methods. For details, please check
http://www.jb51.net/ article/35845.htm

3. When the page is loaded, it is best to perform the creation after the page is loaded.
You can use window.onload, but when adding new elements, unfortunately, browsing The browser executes the window.onload function not only after the DOM tree is built, but also after all images and other external resources are completely loaded and displayed in the browser window. So if a certain image or other resource takes a long time to load, visit The user will see an incomplete page, and a script that relies on dynamically added elements will be executed even before the image is loaded, causing a script error.

The solution is to wait for the DOM to be parsed, and then add the image and Execute our function before the external resource is loaded. Making this implementation feasible in jQuery
Copy the code The code is as follows:

$(document).ready(
function() { testDiv.innerHTML = "
Use dynamically created $(document). ready(function) method
"; }
);

Or use simple syntax:
Copy code The code is as follows:

//jQuery uses the $(function) method
$(
function() { testDiv.innerHTML = "
Use $(function) method
"; }
);

Use $() to wrap our function Yes. And you can bind multiple functions to one page. If you use the traditional window.onload, you can only call one function.

So please use this method to call the function that modifies the DOM. Also note that The difference between document.createElement and innerHTML. If possible, please try to use document.createElement and $("
") to create objects.
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