**
在JavaScript MDN上面看到的一个挺简单的小案例
注意:尽量不要把js文件放到head里面,会监听不到事件
**
// html
<body>
<div>
<label for="customname">输入自定义名字:</label>
<input id="customname" type="text" placeholder="李雷">
</div>
<div>
<label for="metric">公制</label><input id="metric" type="radio" name="measure" value="metric" checked>
<label for="american">美制</label><input id="american" type="radio" name="measure" value="american">
</div>
<div>
<button class="randomize">生成随机笑话</button>
</div>
<!-- 鸣谢:Willy Aguirre 提供的测试代码 -->
<p class="story"></p>
</body>
<!-- 引用js文件 也可以直接写在script标签里面 -->
<script src="./row-text.js"></script>
Javascript
// 1. 定义变量和函数
const customName = document.getElementById('customname');
const randomize = document.querySelector('.randomize');
const story = document.querySelector('.story');
function randomValueFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
var storyText = '今天气温 34 摄氏度,:inserta:出去遛弯。当走到:insertb:门前时,突然就:insertc:。人们都惊呆了,李雷全程目睹但并没有慌,因为:inserta:是一个 130 公斤的胖子,天气又辣么热。';
var insertX = ['怪兽威利','大老爹','圣诞老人'];
var insertY = ['肯德基','迪士尼乐园','白宫'];
var insertZ = ['自燃了','在人行道化成了一坨泥','变成一条鼻涕虫爬走了'];
// 3. 事件监听器和未完成的函数定义
randomize.addEventListener('click', result);
function result() {
var newStory = storyText;
var xItem = randomValueFromArray(insertX);
console.log('随机名字是',xItem)
var yItem = randomValueFromArray(insertY);
var zItem = randomValueFromArray(insertZ);
if(customName.value !== '') {
let name = customName.value;
newStory = newStory.replace('李雷',name);
}
if(document.getElementById("american").checked) {
let weight = Math.round(300);
let temperature = Math.round(94);
newStory = newStory.replace('34 摄氏度',temperature+'华氏度');
newStory = newStory.replace('130 公斤',weight+'磅');
}
newStory = newStory.replace(':inserta:',xItem);
console.log(newStory);
newStory = newStory.replace(':insertb:',yItem);
newStory = newStory.replace(':insertc:',zItem);
newStory = newStory.replace(':inserta:',xItem);
story.textContent = newStory;
story.style.visibility = 'visible';
// return newStory;
}
**
CSS样式
**
body {
font-family: sans-serif;
width: 350px;
}
label {
font-weight: bold;
}
div {
padding-bottom: 20px;
}
input[type="text"] {
padding: 5px;
width: 150px;
}
p {
background: #FFC125;
color: #5E2612;
padding: 10px;
visibility: hidden;
}