赞
踩
场景题:页面上有一个按钮,点击时在后面显示出一个由4位大写字母组成的随机字符串。(考点:Math方法、字符串下标、点击事件、文本内容操作)
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
-
- <button>点击</button><span></span>
- <script>
- let btn = document.querySelector("button");
- let span = document.querySelector("span");
- // 获取26位大写字母
- let arr = [];
- for (let i = 0; i < 26; i++) {
- arr.push(String.fromCharCode(65 + i));//Unicode编码
- }
- let index;//存储索引位置
- btn.addEventListener("click", function () {
- span.textContent = "";
- // 获取4个大写字母
- for (let i = 0; i < 4; i++) {
- index = getRandom(0, arr.length - 1);
- // 使用字符拼接的方式输出到span标签之间
- span.textContent += arr[index];
- }
- })
-
- // 获取随机索引
- function getRandom(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min);
- }
-
- </script>
- </body>
-
- </html>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。