js——闭包的排他思想

版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/82118578
    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>

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/82118578