Closest ()
This method gets the first matching ancestor element, noting that the starting point includes its own element.
In addition, this method is required to pass in a selector expression parameter, and if the argument is not passed in, an empty jquery object is returned.
Note the difference between this method and the parents () method in jquery.
Here's a look at the example:
code is as follows |
copy code |
<div Class= "Demo" > Dream Ploughing Blog <ul> <li> First li</li> <li class= "Li2" > Second li</li> <li> Third li</li> </ul> </div $ ("Ul>li"). Click (function (e) { $ (e.target). Closest ("div"). CSS (" Background-color "," Blue "); }) |
E.target is the element that triggered the Click event (DOM object)
The above jquery code means: For each of the UL directly under the LI element binding order the event, the Click event result is to find the trigger of the event click the element of the nearest DIV element, and then let this div element background color blue.
The result of the jquery code above is that when you click on any LI element, the background color of the div element in the page turns blue.
The code is as follows |
Copy Code |
<style> . demo{ border:2px solid #0000FF; color: #FF0000;p adding:10px; } </style> <div class= "Demo" > Dream Ploughing Blog <ul> <li> First li</li> <li class= "Li2" > Second li</li> <li> a third li</li> </ul> </div> <script> $ ("Ul>li"). Click (function (e) { $ (e.target). Closest ("div"). CSS ("Background-color", "Blue"); }) </script>
|
Add event bindings to it
The code is as follows |
Copy Code |
$ ("Ul>li"). Click (function (e) { $ (e.target). closest (). CSS ("Background-color", "Blue"); }) |
Note: The closest here does not have an incoming parameter.
Running the code above, when you click on the LI element in the page, the background color of the DIV element will not change, because when the closest method does not pass in the parameter, the element must not be taken.
The code is as follows |
Copy Code |
<style type= "Text/css" > . demo{ border:2px solid #0000FF; color: #FF0000;p adding:10px; } </style> <div class= "Demo" > Dream Ploughing Blog <ul> <li> First li</li> <li class= "Li2" > Second li</li> <li> a third li</li> </ul> </div> <script> $ ("Ul>li"). Click (function (e) { $ (e.target). closest (). CSS ("Background-color", "Blue"); }) </script> |
Note: E.target is the target object, E.event is the event that occurs on the target.