javascript 闭包 -- 函数

来源:互联网 发布:山东淘宝代运营 编辑:程序博客网 时间:2024/04/27 15:39

javascript初学者一般将dom函数的设置写成这个样子,随着技能的提高,代码越来越精炼

<html><head></head><body><script>function test(va){   alert(va);}</script><input type = 'button' onclick = test('jsp输出') value = 'aaa'></body></html>

后来   ------       (‘jsp输出’ 可能是特殊字符)

<html><head></head><body><script>function test(va){   alert(va.name);}</script><input type = 'button' onclick = test(this) value = 'aa' name = "jsp 输出"></body></html>

再后来   -----     (javascrip 代码和 html 分离)

<html><head></head><body><input id = 'testid' type = 'button' value = 'aa' name = "jsp 输出"><script>function $(id){   return document.getElementById(id)}$('testid').onclick = function(){    alert(this.name)}</script></body></html>


再后来 

<html><head></head><body><input id = 'testid' type = 'button' value = 'aa' name = "jsp 输出"><script>function $(id){   return document.getElementById(id)}$('testid').onclick = function(){    alert('this.name')}//添加部分var f = $('testid').onclick$('testid').onclick = function(){alert('begin');f();alert('end');}</script></body></html>

再后来    ---------------- (公共代码处理)

<html><head></head><script></script><body><input id = 'testid' type = 'button' value = 'aa' name = "jsp 输出"><script>function InitJsp(){var f = document.body.onload;document.body.onload = function(){if(f != null){f();}if(loadjsp != null){loadjsp();}}}InitJsp();function $(id){   return document.getElementById(id)}$('testid').onclick = function(){    alert('this.name')}function loadjsp(){//添加部分var f = $('testid').onclick$('testid').onclick = function(){alert('begin');f();alert('end');}}</script></body></html>

在后来

<html><head></head>//script 引用//公共jsp引用  (调用InitJsp();)<script></script><body><input id = 'testid' type = 'button' value = 'aa' name = "jsp 输出"><script>$('testid').onclick = function(){    alert('this.name')}function loadjsp(){//添加部分var f = $('testid').onclick$('testid').onclick = function(){alert('begin');f();alert('end');}}</script></body></html>

 

上述javascript在运行中动态修改相应函数的方式,看似炫技,在必要的情况下却能发挥很强大的力量。

比如笔者曾经遇到这样非常常见的需求:

1.每个表单元素(如文本输入框,密码输入框等)在失去焦点事需要对其数据进行校验,如用户名是否长度超长,

是否有不允许存在的字符等。如果校验成功,则在表单元素后显示一个绿色的图片表示正确,如果校验不成功则在显示一个红色的图片。

2.在1的基础上,有些字段如果校验成功则需进一步进行ajax校验,如用户名。需要用ajax在数据库中校验是否存在相同的用户名,如果

校验成功,则在表单元素后显示一个绿色的图片表示正确,如果校验不成功则在显示一个红色的图片。

因为项目这样中用到表单提交的地方非常多,这样的校验需要写成通用的校验函数才能节省开发时间,否则一个小小的需求变动

会引发大面积的修改,怎样只增加一两行代码就能实现上述功能,而且后续的需求修改不会引发大面积的修改?



原创粉丝点击