8. 场景题:页面上有一个按钮,点击时在后面显示出一个由4位大写字母组成的随机字符串。(考点:Math方法、字符串下标、点击事件、文本内容操作)
时间: 2023-05-22 19:03:15 浏览: 125
下面是一个示例代码,实现了一个点击按钮后,在后面显示出一个由4位大写字母组成的随机字符串:
HTML:
```
<button id="btn">生成随机字符串</button>
<div id="result"></div>
```
JS:
```
document.getElementById("btn").onclick = function() {
var str = "";
for (var i = 0; i < 4; i++) {
var code = Math.floor(Math.random() * 26 + 65);
str += String.fromCharCode(code);
}
document.getElementById("result").innerHTML = str;
}
```
当用户点击按钮后,程序使用 Math.random() 方法生成一个 0 到 1 之间的随机浮点数,同时使用 Math.floor() 方法将其转换为 0 到 25 的整数,再加上 65,得到一个 ASCII 码值在 65 到 90 之间的整数,对应着 A 到 Z 的大写字母。然后使用 String.fromCharCode() 方法将其转换为字符,加入到结果字符串中。重复这个过程四次后,将字符串显示在指定的 div 元素中。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)