jQuery判断一个元素是否为另一个元素的子元素(或者其本身)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>新功能测试</title>
</head>
<style type="text/css">
.demo {padding: 30px; height: 300px; position: relative; }
.floatLayer{ position: absolute; top:50px; left: 100px; width: 200px;height: 200px; border: 10px solid #FF3300; padding: 10px }
ol,ul{list-style:none; margin:0; padding:0}
.topic-list li{ float:left; margin-right:15px}
</style>
<body>
<div id="main">
<h1>jQuery判断一个元素是否为另一个元素的子元素的实例页面</h1>
<div id="body" class="light">
<div id="content" class="show">
<h3>演示</h3>
<div class="demo">
<div class="floatLayer"><h4>这是一个浮层</h4> 点击浮层内部警告true<br />点击浮层外部警告false</div>
</div>
</div>
</div>
</div>
<script src="https://lib.baomitu.com/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
//判断:当前元素是否是被筛选元素的子元素
jQuery.fn.isChildOf = function(b){
return (this.parents(b).length > 0);
};
//判断:当前元素是否是被筛选元素的子元素或者本身
jQuery.fn.isChildAndSelfOf = function(b){
return (this.closest(b).length > 0);
};
</script>

<script type="text/javascript">
$(document).click(function(event){
alert($(event.target).isChildOf(".floatLayer"));
});
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xieyongbin/p/10831908.html