The content of this article is about the code analysis of closure performance optimization in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
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>
Optimize performance
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>
Related recommendations:
The above is the detailed content of Code analysis of closure performance optimization in js. For more information, please follow other related articles on the PHP Chinese website!