排他思想

排完思想

需求:有 5 个按钮,点击当前按钮变红,其他按钮恢复默认颜色

<!-- HTML 结构 -->
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
var aBtn = document.querySelectorAll('button');

for(var i = 0; i < aBtn.length; i ++) {
    aBtn[i].onclick = function() {
        // Step1: 先干掉所有人,“排完”
        for(var i = 0; i < aBtn.length; i ++) {
            aBtn[i].style.backgroundColor = '';
        }
        // Step2: 再操作自己的
        this.style.backgroundColor = 'red';
    };
}

排兄思想

<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script>
$("button").on("click", function() {
    // 先操作自己的,再干掉所有的兄弟,“排兄”
    $(this).css("background", "red").siblings().css("background", "");
});
</script>

排上思想

var aBtn = document.querySelectorAll('button');
var prev = 0;

for (var i = 0; i < aBtn.length; i++) {
    aBtn[i].index = i;
    aBtn[i].onclick = function () {
        // Step1: 先干掉上一个,“排上”
        aBtn[prev].style.backgroundColor = "";
        // Step2: 再操作自己的
        this.style.backgroundColor = 'red';
        // Step3: 操作完别忘了把自己也变成“上一个”
        prev = this.index;
    };
}

 优化

let aBtn = document.querySelectorAll('button')
    aBtn.forEach(btn => {
      btn.onclick = function () {
        aBtn.forEach((item, index) => {
          aBtn[index].style.backgroundColor = ''
        })
        this.style.backgroundColor = 'red'
      }
    })

 

posted on 2020-08-25 17:47  huyadi  阅读(376)  评论(0编辑  收藏  举报