您的位置:首页 > Web前端 > JQuery

jquery如何实现点菜单或者菜单里面的对象不隐藏,点菜单外面隐藏

2013-06-01 18:37 375 查看
<!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

Categories: Events >Event
Object

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 compare
event.target
to
this
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.

注意target可能是注册了事件的element或者是他的后代。你可以用

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 ] )

selector
Type: Selector
A 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://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element?page=1&tab=oldest#tab-top

http://api.jquery.com/parents/

http://api.jquery.com/event.target/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: