JavaScript 操作选中当前的li元素并给他添加select类
JavaScript 操作选中当前的li元素并给他添加select类。之前都是使用jquery写的,今天使用JavaScript写一个。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> li{cursor:pointer;} .select{background:pink;} </style> </head> <body> <ul> <li>这是菜单1</li> <li>这是菜单2</li> <li>这是菜单3</li> <li>这是菜单4</li> <li>这是菜单5</li> <li>这是菜单6</li> <li>这是菜单7</li> <li>这是菜单8</li> </ul> </body> </html> <script type="text/javascript"> window.onload = function (){ var aLi = document.getElementsByTagName("li"); console.log(aLi); var i = 0; for (i = 0; i < aLi.length; i++){//得到li的长度 aLi[i].onclick = function () { for (i = 0; i < aLi.length; i++) { aLi[i].className = aLi[i].className.replace(/\s?select/,"");//替换select为空 console.log(aLi[i]); } this.className += "select";//添加select类 }; } }; </script>
运行结果: