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

<!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.

注意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.

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/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值