javascript中的事件时通过事件监听的机制来实现,但是在某些情况下需要使用javascript手动触发事件。
<input type="button" id="btn1" name="" value="test" onclick="alert('click');" />
<input type="button" id="" name="" value="fire" onclick="fire();" />
如果fire按钮来触发test按钮的onclick事件,fire方法可以这么写的:
        function fire(){
            var evt = window.event?window.event:fire.caller.arguments[0];//获取event对象
            var o= document.getElementById("btn1");
            if(o.fireEvent){//IE
                o.fireEvent("onclick",evt);//IE下可以直接使用fireEvent方法触发事件
            }else{//other browsers
                //创建一个对象
                var event = document.createEvent("MouseEvents");
                            
                //设置event对象属性
                event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0, 
                                     false, false, false, false, 0, null);
                            
                //触发事件
                o.dispatchEvent(event); 
            }
        }
最开始看到这些代码是在Wrox.Professional.JavaScript.For.Web.Developers.2nd书中,我迅速想到jquery中是否有类似的实现?事实上我连dispatchEvent都没有找到
 
事实上我想复杂了,要触发onclick事件,直接用oBtn.click()方法即可,没有浏览器兼容问题。jquery中就是直接用这个方法的。
$(function(){
            $("#jqFire").click(function(){
                $("#btn1").click();//works
                o.click();//also works
            });
        });
关于上面提到的createEvent/initMouseEvent/dispatchEvent/fireEvent方法可以参考下列资料:
http://stackoverflow.com/questions/911586/javascript-simulate-mouse-over-in-code
http://stackoverflow.com/questions/460644/trigger-an-event-with-prototype 这个帖子介绍了几种事件触发的方法
http://jehiah.cz/a/firing-javascript-events-properly 一个触发事件方法封转
http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6163 jquery.simulate.js的源代码