zoukankan      html  css  js  c++  java
  • js 自定義event

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title>Event對象敘述  自定義事件CustomEvent</title>
    	</head>
    	<body>
    		<!--
            	
            	描述:事件发生以后,会产生一个事件对象,作为参数传给监听函数。浏览器原生提供一个Event对象,
            	所有的事件都是这个对象的实例,或者说继承了Event.prototype对象。
            	  點擊->var clickEvent = new Event('click') ->存在addEventListener監聽函數->執行監聽函數
            	   將clickEvent對象作爲參數傳遞過去
            -->
            <!--
            	var eve = new Event('look',{
    			"bubbles":false,
    			"cancelable":false
    		});
    		document.dispatchEvent(eve); //document調用 Event是dom下的一部分
            -->
            <div>父div
            <h1>1111111111111</h1>
            </div>
    	</body>
    	<script>
    		var eve = new CustomEvent('look',{
    			"bubbles":false,
    			"cancelable":false 
    		});
    		
    		var h1=document.querySelector("h1");
    		var div1 =document.querySelector("div");
    		h1.addEventListener('look',function(ev){
    			console.info('user defined event happen');
    			var bubble=ev.bubbles;
    			console.error(bubble)//false 非冒泡類型
    		},false) 
    //		div1.addEventListener('look',function(){
    //			console.error("parent element div attach")
    //		},true)//useCapture 情況下執行 且先于h1執行
    
    		div1.addEventListener('look',function(){
    			console.error("parent element div attach")
       		},false)//useCapture 為false 冒泡情況下才執行   --->結果:由於h1的bubbles=false 不冒泡  因此div1的事件不觸發
    		h1.dispatchEvent(eve);//user defined event happen 
    		//手動觸發事件執行
    		
    	</script>
    </html>
     
    

     自定義事件傳參數

    var myEvent = new CustomEvent('myevent', {
      detail: {
        foo: 'bar'
      },
      bubbles: true,
      cancelable: false
    });
    
    el.addEventListener('myevent', function (event) {
      console.log('Hello ' + event.detail.foo);
    });
    
    el.dispatchEvent(myEvent);
    
  • 相关阅读:
    反转链表 16
    CodeForces 701A Cards
    hdu 1087 Super Jumping! Jumping! Jumping!(动态规划)
    hdu 1241 Oil Deposits(水一发,自我的DFS)
    CodeForces 703B(容斥定理)
    poj 1067 取石子游戏(威佐夫博奕(Wythoff Game))
    ACM 马拦过河卒(动态规划)
    hdu 1005 Number Sequence
    51nod 1170 1770 数数字(数学技巧)
    hdu 2160 母猪的故事(睡前随机水一发)(斐波那契数列)
  • 原文地址:https://www.cnblogs.com/bawang/p/9104796.html
Copyright © 2011-2022 走看看