今天在编写分离式JavaScript开发时产生的想法,其实这个问题早就有了而且一直都在困扰着执着的分离式编程写法的人们:
完全分离在实际工作中真的有必要吗?
在 a 标签 定义 onclick 事件,利用 cookie 实现判断用户是否登录。下面是部分代码:
var
FavoriteClick
=
function
() {
var links = document.getElementsByTagName( ' a ' );
if ( ! links) return ;
for (i = 0 ;i < links.length;i ++ ) {
if (links[i].className == ' addToFavourite ' ) {
links[i].onclick = function () {
IsCookieName( ' wy ' );
};
}
}
}
var links = document.getElementsByTagName( ' a ' );
if ( ! links) return ;
for (i = 0 ;i < links.length;i ++ ) {
if (links[i].className == ' addToFavourite ' ) {
links[i].onclick = function () {
IsCookieName( ' wy ' );
};
}
}
}
上面就是利用DOM定位元素而写的,而这样的程序受算法复杂度而影响效率,所以,不分离式编程写法:用 οnclick="FavoriteClick(this);"只需要短短的几行:
var
FavoriteClick
=
function
(obj) {
if (obj.className == ' addToFavourite ' ) {
IsCookieName( ' wy ' );
}
return false;
}
if (obj.className == ' addToFavourite ' ) {
IsCookieName( ' wy ' );
}
return false;
}
这种是DOM触发的事件,还无须等待载入完不完毕。
前端专家棕熊对效率和需求都能兼顾的一些想法(用代码说明):
<
script type
=
"
text/javascript
"
>
function demo(obj) {
obj.value = Math.random();
}
< / script>
< input type = " button " value = " demo " onclick = " demo(this) " / >
< input type = " button " value = " demo " onclick = " demo(this) " / >
< input type = " button " value = " demo " onclick = " demo(this) " / >
function demo(obj) {
obj.value = Math.random();
}
< / script>
< input type = " button " value = " demo " onclick = " demo(this) " / >
< input type = " button " value = " demo " onclick = " demo(this) " / >
< input type = " button " value = " demo " onclick = " demo(this) " / >
ps.本人执着于脚本分离式编程思想哦~!