javascript trigger触发事件

时间:2022-05-30 07:06:21
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<div id="div1" onclick="alert(11)" style="width:100px; height:100px; background:red;"></div>
</body>
</html>
<script>
function trigger(el,type){
try{
//w3c
var evt = document.createEvent('Event');
evt.initEvent(type,true,true);
el.dispatchEvent(evt);
}catch(e){
//ie
el.fireEvent('on' + type);
}
}
var div = document.getElementById('div1');
trigger(div,'click');
</script>