closest(expr|object|element)

closest(expr|object|element)

Outline

jQuery 1.3 added. From the beginning of the element itself, step by step to match the parent element, and returns the first match. . Marble platform production plant

closest first checks whether the current element matches, if the match will directly return to the element itself. If not then look up the parent element, up layer by layer, until it finds a matching selector elements. If none are found an empty jQuery object is returned.

The main difference between the closest and parents are: 1, the former from the current element to start looking for matches, which start from the parent element matching looking; 2, look up the former step by step, until it finds a matching element ceased after the latter has been up to find until the root element, and these elements into a temporary set, and then given to the selector filter expression; 3, 0 or 1 returns the former elements, which may contain 0, 1, or more element.

closest commissioned useful for handling events.

.closest (selectors [, context]) method from jQuery 1.7 start, no longer recommend using this method, but before jQuery 1.7 can still be used. This method will be used jQuery plugin authors or internal use.

parameter

exprString,ArrayV1.3

Filter elements for expression. jQuery 1.4 starts, may pass a string array, for finding a plurality of elements.

expr,[context]StringV1.4

expr: Expression Filter subelements for

context: DOM element in which a matching element can be found. If there is no context in the circumstances by the jQuery settings it will be used.

jQuery object objectV1.6

A matching element for jQuery object

element DOMElement V1.6

A matching element for DOM elements.

Examples

description:

How to use the closest show to find multiple elements

HTML code:
<ul><li></li><li></li></ul>
jQuery code:
$("li:first").closest(["ul", "body"]);
result:
[ul, body]

description:

How to use the closest show to complete the event delegate.

HTML code:
<ul>
    <li><b>Click me!</b></li>
    <li>You can also <b>Click me!</b></li>
</ul>
jQuery code:
$(document).bind("click", function (e) {
    $(e.target).closest("li").toggleClass("hilight");
});

Guess you like

Origin www.cnblogs.com/furuihua/p/12015417.html