欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript自定义事件

程序员文章站 2022-04-27 12:58:42
...
一言不合上代码
<input value="aa" type="text" id="mytest" />
<script type="text/javascript">
  var event; // The custom event that will be created
  var element=document.getElementById("mytest");
  if (document.createEvent) {//创建事件
    event = document.createEvent("HTMLEvents");
    event.initEvent("dataavailable", true, true);
    console.log("----->创建事件");//+writeObj(event)
  } else {
  	console.log("bbbbbb--b");
    event = document.createEventObject();
    event.eventType = "dataavailable";
  }
  event.eventName = "dataavailable";
  //绑定事件
  document.addEventListener("dataavailable", function(e) {
    console.log("时间发生的时候:"+e.srcElement.value); 
  });
  if (document.createEvent) {//触发事件
  	console.log("---->>>触发事件");//+writeObj(event)
    element.dispatchEvent(event);
  } else {
  	console.log("bbb--bbbbbb");
    element.fireEvent("on" + event.eventType, event);
  }
  
//------------
  function writeObj(obj){ 
	 var description = ""; 
	 for(var i in obj){ 
		  var property=obj[i]; 
		  description+=i+" = "+property+"\n"; 
	 } 
	 //console.log(description); 
	 return description;
  } 
</script>


参考
http://*.com/questions/2490825/how-to-trigger-event-in-javascript