点击页面中的按钮随机产生"北京","上海","广州","深圳","成都","西安","南京","济南","太原","呼和浩特","西宁","郑州"中的一个
时间: 2023-08-31 21:12:23 浏览: 77
好的,我可以为您提供一个随机产生城市的代码,您可以在网页中使用:
```javascript
var cities = ["北京","上海","广州","深圳","成都","西安","南京","济南","太原","呼和浩特","西宁","郑州"];
var randomCity = cities[Math.floor(Math.random()*cities.length)];
console.log(randomCity);
```
这个代码会从数组 `cities` 中随机选择一个元素,也就是一个城市名,并将其打印在控制台中。如果您需要将其显示在网页上,可以将 `console.log(randomCity);` 替换为将 `randomCity` 值赋给一个 HTML 元素的代码。
相关问题
用CSDN写一个代码,目的是点击页面中的按钮随机产生"北京","上海","广州","深圳","成都","西安","南京","济南","太原","呼和浩特","西宁","郑州"中的一个
以下是用HTML、CSS和JavaScript实现的代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机城市选择器</title>
<style>
button {
padding: 10px;
font-size: 20px;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>随机城市选择器</h1>
<p>点击下面的按钮,随机选择一个城市:</p>
<button id="city-btn">选择城市</button>
<script>
var cities = ["北京", "上海", "广州", "深圳", "成都", "西安", "南京", "济南", "太原", "呼和浩特", "西宁", "郑州"];
var btn = document.getElementById("city-btn");
btn.onclick = function() {
var randomIndex = Math.floor(Math.random() * cities.length);
alert("你选择的城市是:" + cities[randomIndex]);
};
</script>
</body>
</html>
```
这段代码定义了一个包含12个城市名称的数组`cities`,并用`Math.random()`函数和`Math.floor()`函数生成一个0到11之间的随机整数作为数组的索引,最后将随机选择的城市名称以弹窗的形式展示出来。用户只需点击页面中的“选择城市”按钮即可随机选择一个城市。
使用JavaScript的Date对象,当点击网页中按钮时生成随机日期,并输出到页面中
好的,可以使用以下代码实现:
HTML:
```
<button onclick="generateRandomDate()">生成随机日期</button>
<p id="random-date"></p>
```
JavaScript:
```
function generateRandomDate() {
// 生成随机年份
const year = Math.floor(Math.random() * (2021 - 1900) + 1900);
// 生成随机月份
const month = Math.floor(Math.random() * 12) + 1;
// 根据月份和年份计算出当月的天数,从而生成随机日期
const daysInMonth = new Date(year, month, 0).getDate();
const day = Math.floor(Math.random() * daysInMonth) + 1;
// 将日期格式化为字符串并输出到页面中
const date = new Date(year, month - 1, day);
const formattedDate = date.toLocaleDateString();
document.getElementById("random-date").innerHTML = formattedDate;
}
```
这段代码会生成一个按钮和一个段落元素,当点击按钮时会调用 `generateRandomDate` 函数,该函数会生成一个随机日期并将其输出到页面中。具体实现是先生成随机年份和月份,然后根据月份和年份计算出当月的天数,再生成随机日期。最后,使用 `toLocaleDateString()` 方法将日期格式化为字符串并将其输出到页面中。