Home > Article > Web Front-end > Usage examples of find and each methods in Jquery_jquery
The example in this article describes the usage of find and each methods in Jquery. Share it with everyone for your reference. The details are as follows:
1. find() method
The jquery selector is very powerful. Using the naming convention of css, you can find the desired element faster and more conveniently.
For example:
$("#id") $("#"+"id") $(this) $(element)
Wait, as long as you use it flexibly, you can explode into powerful shapes.
However, in actual use, I still feel there are some shortcomings.
If you want to find a specific element under a certain element, just relying on the above method, you must traverse the element obtained by $("#id") to obtain its sub-elements. As a result, it becomes extremely cumbersome and the amount of code is also very large.
So this requires the use of the find() method.
$("#id").find("#child"); $("#id").find(".child"); $("#id").find("input[type='image']");
Very convenient and easy to use.
In addition to the find() method above, there is also a way to find child elements.
$(".child",parent);
This method has the same result as the find() method and is more concise.
Let’s give an example:
function(table){ $("tr",table).css("background-color","red"); }
This method facilitates code reuse and is more consistent with closure writing.
2. each() method
Arrays are often used sometimes. Before I knew the each() method, if I encountered array traversal, I would usually write like this:
var arr = new Array(); arr.push(1); arr.push(2); arr.push(3); for(var i =0;i<arr.length;i++) { (function(m){ console.log(this); })(i); }
How cumbersome! ! Now that each() is available, life becomes easier.
The above code only requires one sentence.
var arr = new Array(); arr.push(1); arr.push(2); arr.push(3); arr.each(function(){ console.log(this); });
After using each, the structure immediately becomes simple and elegant.
I hope this article will be helpful to everyone’s jQuery programming.