<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <input type="button" value="变色" id="btn" /> <ul id="uu"> <li>爆炒助教</li> <li>油炸班主任</li> <li>清蒸小苏</li> <li>红烧班长</li> <li>红烧肉</li> <li>糖醋排骨</li> <li>凉拌秋葵</li> <li>鱼香胡萝卜丝</li> </ul> <script src="common.js"></script> <script type="text/javascript"> //定义一个计数器 var count = 0; //获取所有的ul var ulObj = my$("uu"); //获取ul的子节点 var nodes = ulObj.childNodes; //添加点击事件 my$("btn").onclick = function() { //遍历所有的节点 for (var i = 0; i < nodes.length; i++) { //判断所有的li节点 if (nodes[i].nodeType == 1 && nodes[i].nodeName == "LI") { nodes[i].style.backgroundColor = count % 2 == 0 ? "red" : "yellow"; count++; } } }; </script> </body> </html>
效果: