再一次扩展,得到了上面的方法,可以调指定方法,也可以传参数了,似乎没问题了,但是在firefox中,event是不能用window.event来取的,必须要传event过去,真麻烦,再改改吧.
Version 5:
| <script language="javascript" type="text/javascript"> function SomeClass(el) { if(typeof(el) == "string") { el = document.getElementById(el); } el.onclick = this.GetFunctionWithEvent(this, "ShowEvent", "Hello, Robot!"); } SomeClass.prototype = { Show : function() { alert("Say Hello!"); }, ShowAny : function(any) { alert(any); }, ShowEvent : function(e,any) { var el = e ? e.target : event.srcElement; var x = e ? e.pageX : event.clientX; var y = e ? e.pageY : event.clientY; alert(any + "\r\nElement : " + el.id + "\r\nPosition : " + x + " | " + y); }, GetFunction : function(Variable, Method, Parameter) { return function() { Variable[Method](Parameter); } }, GetFunctionWithEvent : function(Variable, Method, Parameter) { return function(e) { Variable[Method](e, Parameter); } } } window.onload = function() { new SomeClass("btnDemo"); } </script> <input type="button" value="Hello" id="btnDemo" /> |
这样,你的方法在firefox中也可以用event了,取鼠标的事件源dom就可以这样了:
var el = e ? e.target : event.srcElement;
firefox里的event跟ie里的event有啥区别就不用我说了吧.
最后我又碰到了这么一个问题,如果我在一个element的onclick上要绑定多个事件怎么办呢?
Version Final:
| <script language="javascript" type="text/javascript"> function SomeClass(el) { if(typeof(el) == "string") { el = document.getElementById(el); } el.onclick = this.GetFunction(this, "Show|ShowAny", "Hello, Robot!"); } SomeClass.prototype = { Show : function() { alert("Say Hello!"); }, ShowAny : function(any) { alert(any); }, GetFunction : function(Variable, Method, Parameter) { return function() { if(Method.indexOf("|") > -1) { var MethodArray = Method.split("|"); for(var x = 0; x < MethodArray.length; x++) { Variable[MethodArray[x]](Parameter); } } else { Variable[Method](Parameter); } } }, GetFunctionWithEvent : function(Variable, Method, Parameter) { return function(e) { if(Method.indexOf("|") > -1) { var MethodArray = Method.split("|"); for(var x = 0; x < MethodArray.length; x++) { try { Variable[MethodArray[x]](e, Parameter); } catch(err) { continue; } } } else { Variable[Method](e, Parameter); } } } } window.onload = function() { new SomeClass("btnDemo"); } </script> <input type="button" value="Hello" id="btnDemo" /> |
这里面使用|来分割方法,加入了event,可以绑定多个方法了,也加入了try...catch...避免一个出错,其它的也跟着一起挂.暂时没能想到升级版了.呵呵.

