Js获取事件对象代码 |
本文标签:事件对象 一般做法: 复制代码 代码如下: <input type="button" id="test" value="点我测试" /> <script type="text/javascript"> var testBtn = document.getElementById(test); testBtn.onclick = testFun; function testFun(e) { var evt = e || window.event; alert(evt); } </script> 或者: 复制代码 代码如下: <input type="button" id="test" value="点我测试" /> <script type="text/javascript"> var testBtn = document.getElementById(test); if(window.addEventListener) { testBtn.addEventListener(click, testFun, false); } else if(window.attachEvent) { testBtn.attachEvent(onclick, testFun); } function testFun(e) { var evt = e || window.event; alert(evt); } </script> 返回的值都是 “[object Event]“ 。 但如果是这种方式呢? 复制代码 代码如下: <input type="button" id="test_1" value="点我测试" onclick="testFun_1()" /> <script type="text/javascript"> function testFun_1() { //此处如何获得? } </script> “内事不决问百度,外事不决问谷歌”, 此言不虚 。搜索了下,答案还真不少,不过大多数雷同(可能是巧合) 。 http://www.jb51.net/article/19408.htm http://www.cnblogs.com/cuixiping/archive/2008/04/13/1150847.html 愚公 的这个文章(貌似转帖)还是颇有见解的 。 复制代码 代码如下: <input type="button" id="test_1" value="点我测试" onclick="testFun_1()" /> <script type="text/javascript"> function testFun_1() { var evt = getEvent(); alert(evt); } function getEvent(){ if(window.event) return window.event; //这里用对象检测更为妥当 func=getEvent.caller; while(func!=null){ var arg0=func.arguments[0]; if(arg0){ if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)){ return arg0; } } func=func.caller; } return null; } </script> 一般来说,很少用到这种嵌入式的写法(js写在html标签中 onclick="testFun_1()"),也不推荐使用这种方法,会造成维护和开发的麻烦 。 |