ES6函式實現排它兩種寫法解析
阿新 • • 發佈:2020-05-14
排它思想:清除其它所有的沒有選中元素的樣式,只設置當前選中元素的樣式
html程式碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> <li class="current">我是第1個li</li> <li>我是第2個li</li> <li>我是第3個li</li> <li>我是第4個li</li> <li>我是第5個li</li> <li>我是第6個li</li> <li>我是第7個li</li> <li>我是第8個li</li> </ul> </body> </html>
css程式碼
<style> *{ margin: 0; padding: 0; } ul{ list-style: none; margin: 100px auto; width: 300px; height: 400px; border: 1px solid #000; } ul>li{ font-size: 30px; font-weight: bold; margin-bottom: 10px; cursor: default; } .current{ background-color: brown; } </style>
JavaScript程式碼
<script> /* // es6之後的寫法 let items = document.querySelectorAll("li"); let previousIndex = 0; for (let i = 0; i < items.length; i++) { // let currentItem = items[i]; items[i].onclick = function () { items[previousIndex].className = ""; this.className = "current"; previousIndex = i; // console.log(previousIndex); }; } */ // es6之前的寫法 var items = document.querySelectorAll("li"); var previousIndex = 0; for (var i = 0; i < items.length; i++) { (function (index) { items[index].onclick = function () { items[previousIndex].className = ""; this.className = "current"; previousIndex = index; }; })(i); } </script>
執行效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。