<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html id="a1">
<head>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.f{}
</style>
</head>
<body id="a2">
<script type="text/javascript">
$(document).ready(function(){
$("html").click(function(event){
alert($(event.target).attr("id"));
alert($(event.target).parents().each(function(){
alert($(this).attr("id"));}));
if(!$(event.target).is("#a4") && !$(event.target).parents("#a4").is("#a4")){
alert(event.target.nodeName);
}
});
});
</script>
<div id="a3" class="f">
cccc
<div id="a4" class="f">aaa
<p id="a5">bbb</p>
</div>
</div>
</body>
</html>
event.target
event.targetReturns:Element
Description: The DOM element that initiated the event.
-
version added: 1.0event.target
The target
property can be the element that registered for the event or a descendant of it. It is often useful to compareevent.target
tothis
in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
alert($(event.target).attr("id"));
体会,所以不能光用
!$(event.target).is("#a4")
判断,还需要
!$(event.target).parents("#a4").is("#a4")
判断,因为不一定is("#a4"),还可能是他的 a descendant of it
.parents( [selector ] )Returns:jQuery
Description: Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
-
version added: 1.0.parents( [selector ] )
-
selectorType: SelectorA string containing a selector expression to match elements against.
-
Given a jQuery object that represents a set of DOM elements, the.parents()
method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones.When multiple DOM elements are in the original set, the resulting set will be inreverse order of the original elements as well, with duplicates removed.
.parents()方法会搜遍这些elements 在DOM树里的祖先,并构建一个新的jquery对象从匹配的elements里,从最近的父element向上,这些对象是被返回的按照最近的父element到更外面的。你可以用
alert($(event.target).parents().each(function(){
alert($(this).attr("id"));}));
来体会。
http://api.jquery.com/parents/
http://api.jquery.com/event.target/