本篇文章给大家带来的内容是关于js中闭包性能优化的代码解析,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
window.onload=function () { var btn=document.getelementsbytagname('button'); for(var i=0;i<btn.length;i++){ (function (index) { btn[index].onclick=function () { //类似css中的ul:hover li for(var j=0;j<btn.length;j++){ btn[j].style.backgroundcolor='';//清空全部 } //类似css中的ul>li:hover this.style.backgroundcolor='orange';//设置当前的 } })(i); } }<button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button>
优化性能
window.onload = function () { var btn = document.getelementsbytagname('button'); var lastone = 0; for (var i = 0; i < btn.length; i++) { (function (index) { //index就是i btn[index].onmouseover=function () { //清除上一个 btn[lastone].style.backgroundcolor= ''; //设置现在的 this.style.backgroundcolor = 'orange'; //赋值上一个 lastone = index; }; btn[index].onmouseout=function () { this.classname=''; } })(i); } }<button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button><button>按钮</button>
相关推荐:
js闭包 和 prototype
js闭包的使用
以上就是js中闭包性能优化的代码解析的详细内容。