年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1643|回复: 0

[jQuery] 14、jQuery事件处理之事件委派使用示例

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2016-2-21 11:51:23 | 显示全部楼层 |阅读模式
    [HTML] 纯文本查看 复制代码
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8"/>
    	<script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
    	<style type="text/css">
    		html,body{
    			text-align: center;
    			font-size: 20px;
    		}
    		div{
    			margin: 0 auto;
    			border: 1px solid black;
    		}
    		#cn{
    			float: left;
    			margin: 50px;
    			width: 420px;
    			height: 340px;
    			line-height: 40px;
    		}
    		#bj{
    			width: 340px;
    			height: 260px;
    		}
    		#hd{
    			width: 260px;
    			height: 180px;
    		}
    		#ppc{
    			width: 180px;
    			height: 95px;
    		}
    		#usa{
    			float: left;
    			margin: 50px;
    			width: 420px;
    			height: 340px;
    		}
    		
    	</style>
    	<script>
    	$(document).ready(function(){
    		/*
    		$('input').focus(function(){
    			$('#ppc').append("<span>Sian</span>");
    		});
    		$('#ppc').click(function(){
    			// 1、trigger模拟鼠标事件,triggerHandler只执行相关事件
    			// 2、triggerHandler只匹配第一个对象元素执行相关事件
    			// 3、triggerHandler返回值为undefined
    			$('input').trigger('focus');
    			$('input').triggerHandler('focus');
    		});
    		// 从性能上说,绑定太多的事件处理函数将影响性能
    		$('#cn').click(function(event){
    			alert("cn");
    			event.stopPropagation();
    		});
    		$('#bj').click(function(event){
    			alert("bj");
    			event.stopPropagation();
    		});
    		$('#hd').click(function(event){
    			alert("hd");
    			event.stopPropagation();
    		});
    		$('#ppc').click(function(event){
    			alert("ppc");
    			event.stopPropagation();
    		});
    		*/
    		// 通过绑定一个事件处理函数,统一接收事件
    		$('#cn').click(function(event){
    			var elem = $(event.target);
    			if (elem.is('#cn')) alert("cn");
    			if (elem.is('#bj')) alert("bj");
    			if (elem.is('#hd')) alert("hd");
    			if (elem.is('#ppc')) alert("ppc");
    		});
    	});
    	</script>
    </head>
    <body>
    	<div id="cn">
    		<span>中国</span>
    		<div id="bj">
    			<span>北京</span>
    			<div id="hd">
    				<span>海淀</span>
    				<div id="ppc">
    				<span><a href="http://www.baidu.com">[url]www.ppc.com[/url]</a></span>
    				<input type="text"/>
    				</div>
    			</div>
    		</div>
    	</div>
    	<div id="usa">
    		<span>美国</span>
    	</div>
    </body>
    </html>

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-4-30 01:46 , Processed in 0.045452 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表