prototype里Form.Element.focus(element) 方法是否实现错误?
今天上午没事做,在公司拿着买到的 <<prototype与script.aculo.us终极揭秘>>一书看,无意中发现了一个比较有趣的问题,不知道是不是 prototype.js自己的bug,拿上来让各位鉴定一下。
参照prototype.js的官方的api文档,Form.Element.focus(element) -> HTMLElement,他的意思应该是调用这个focus()方法之后返回的是应该是一个被prototye扩张的 HTMLElement,然后可以拿着返回的对象可以继续进行链式调用。可事实上并非如此。我自己测试了一把。下面的代码给的不全。要测试的话需要自己补全。
<script type="text/javascript"> function test_focus(){ $("clickme").observe("click",function(){alert(Object.isString(Form.Element.focus('username')))Form.Element.focus('username').disable().setValue("hahahaha"); });} document.observe("dom:loaded",test_focus) </script> <body> <form id="login"> username : <input type="text" id="username" value="hehehehe"><br>password : <input type="text" id="password"><br><input type="button" value="click me" id="clickme"><br> </form> </body>
上面的代码运行到alert()部分的时候,会提示true,也就是说他返回的是一个String,然后会报出一个Form.Element.focus("username").disable is not a function的错误。
查看prototype.js的源代码,我们看到这个方法的定义,他其实就是直接返回了传进去的element,根本就没做扩展,所以所谓的链式编程到这里就不能继续下去了。
Form.Element = { focus: function(element) { $(element).focus(); return element; }, select: function(element) { $(element).select(); return element; } };
我直接把它hack掉之后上面的代码就可以正常运行了
Form.Element = { focus: function(element) { $(element).focus(); return $(element); }, select: function(element) { $(element).select(); return $(element); } };
我不知道这是不是prototype.js的bug,我这样的修改也只能说能测试通过我写的demo,所以拿出来供大家谈论一下。
setValue: function(element, value) { element = $(element); var method = element.tagName.toLowerCase(); Form.Element.Serializers[method](element, value); return element; },
<script src="prototype-1.6.0.3.js" type="text/javascript"> </script><script type="text/javascript"> function test_focus() { $("clickme").observe("click",function(){ //alert(Object.isString(Form.Element.focus('username'))) Form.Element.disable('username'); Form.Element.setValue('username',"hahahaha"); }); } document.observe("dom:loaded",test_focus) </script> <body> <form id="login"> username : <input type="text" id="username" value="hehehehe"><br> password : <input type="text" id="password"><br> <input type="button" value="click me" id="clickme"><br> </form> </body>activate: function(element) { element = $(element); try { element.focus(); if (element.select && (element.tagName.toLowerCase() != 'input' || !['button', 'reset', 'submit'].include(element.type))) element.select(); } catch (e) { } return element; }