This article analyzes the conversion and difference between DOM objects and jQuery objects with examples. Share it with everyone for your reference. The specific analysis is as follows:
jQuery Hello World program:
Comparison of $(document).ready and window.onload
First look at window.onload:
The latter method will overwrite the previous method, that is, only one bubble will be displayed in the end, the one of World.
If $(document).ready is used, the methods will be concatenated, that is, the Hello alert will be displayed first, and then the World alert will be displayed.
This way you can associate multiple methods.
Another small difference is that the execution of the ready method will be slightly earlier. width.onload will wait for the DOM to be ready and all binding to be completed, while ready can only prepare the DOM, and other work may not be done yet.
Example: Attach onclick event to each hyperlink object
First, add multiple hyperlink objects to the body:
Note that I made a mistake here. I originally thought that the number of alerts would increase, but the actual result was that each alert was 4.
This is because js does not have a block-level scope , and the variable i refers to the one in for, which becomes 4 after the loop. In other words, the value of i is only taken when the onclick event occurs, of course. It’s 4.
Use jQuery to implement this function below:
The $() symbol in jQuery will get all the appropriate elements in the page.
So the above code implies the traversal process and adds an event processing function to each element.
The click method is a method provided by the jQuery object.
onclick is a property of the DOM object.
Many attributes in DOM become methods in jQuery.
Mutual conversion and difference between DOM objects and jQuery objects
Look at an example, first add a p tag:
Click Me!
First get a DOM object, and then convert it into a jQuery object:
You can also obtain a jQuery object first and then convert it into a DOM object:
//way 2:
var domClickMe2 = clickMejQuery.get(0);
alert("dom2: " domClickMe2.innerHTML);
Note again: $() in jQuery obtains an array of all elements that meet the conditions.
Small summary:
$("string") will return an array of all elements that meet the conditions, where:
The string starts with #, indicating id;
The string starts with ., indicating the CSS class name;
If the above two situations are not the case, change the string to represent the tag name.
$(DOM object) can get a jQuery object.
I hope this article will be helpful to everyone’s jQuery programming.