Home > Web Front-end > JS Tutorial > Code analysis of closure performance optimization in js

Code analysis of closure performance optimization in js

不言
Release: 2018-08-28 16:32:27
Original
1439 people have browsed it

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=&#39;&#39;;//清空全部
                    }                    
                    //类似css中的ul>li:hover
                    this.style.backgroundColor=&#39;orange&#39;;//设置当前的
                }
            })(i);
        }
    }

<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
Copy after login

Optimize performance

    window.onload = function () {
        var btn = document.getElementsByTagName(&#39;button&#39;);        
        var lastOne = 0;        
        for (var i = 0; i < btn.length; i++) {
            (function (index) { //index就是i
                btn[index].onmouseover=function () {
                    //清除上一个
                    btn[lastOne].style.backgroundColor= &#39;&#39;;                    
                    //设置现在的
                    this.style.backgroundColor = &#39;orange&#39;;                    
                    //赋值上一个
                    lastOne = index;
                };
                btn[index].onmouseout=function () {
                    this.className=&#39;&#39;;
                }
            })(i);
        }
    }

<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
<button>按钮</button>
Copy after login

Related recommendations:

js closure and prototype

JS closure Package usage

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template