html和css部分
<style>
.lis_ {
width: 100px;
height: 100px;
line-height: 100px;
float: left;
list-style: none;
margin-left: 15px;
text-align: center;
margin-bottom: 10px;
}
</style>
</head>
<body>
<button id="btn">随机生成10个li</button>
<ul id="ul_">
</ul>
</body>
</html>
js部分
<script>
// 找到id为btn的button按钮
var btn = document.getElementById('btn');
// 创建数组
var colors = ['red', 'green', 'blue', 'pink', 'aqua', 'yellow'];
// 找到ul
var ul_ = document.getElementById('ul_');
btn.onclick = function () {
ul_.innerHTML = '';//清空原先的li
for (var i = 0; i < 10; i++) {
// 创建li
var lis = document.createElement('li');
// 生成随机颜色
var index = Math.floor(Math.random() * 5);
lis.style.backgroundColor = colors[index];
// 生成数字
lis.innerHTML = i + 1;
lis.className = 'lis_';
ul_.appendChild(lis);
}
}
</script>