先在这记录一下问题哈
明明可以这样
<button οnclick="displayDate()">点我</button>
却为什么要这样啊-->通过class获取button 赋予onclick
今天(190711)我找到原因了!
具体原因是:便于维护、将您的编程逻辑与内容分离也会使您的站点对搜索引擎更加友好。
具体博客说明:https://blog.csdn.net/ifnotcorrect/article/details/95505428
//以下是通过class获取 button 赋予 onclick事件属性
1. 按钮
<button class="randomize">随机生成笑话</button>
2. 获取按钮
const randomize = document.querySelector('.randomize');
3. 给按钮添加事件监听
randomize.addEventListener('click', result);
4. 监听函数
function result() {
let newStory, xItem, yItem, zItem, name;
if (document.getElementById('cn').checked) {
newStory = storyTextZh;
xItem = randomValueFromArray(insertA);
yItem = randomValueFromArray(insertB);
zItem = randomValueFromArray(insertC);
newStory = newStory.replace(':inserta:', xItem);
newStory = newStory.replace(':inserta:', xItem);
newStory = newStory.replace(':insertb:', yItem);
newStory = newStory.replace(':insertc:', zItem);
if (customName.value !== '') {
name = customName.value;
newStory = newStory.replace('李雷', name);
}
} else {
newStory = storyText;
xItem = randomValueFromArray(insertX);
yItem = randomValueFromArray(insertY);
zItem = randomValueFromArray(insertZ);
newStory = newStory.replace(':insertx:', xItem);
newStory = newStory.replace(':insertx:', xItem);
newStory = newStory.replace(':inserty:', yItem);
newStory = newStory.replace(':insertz:', zItem);
if (customName.value !== '') {
name = customName.value;
newStory = newStory.replace('Bob', name);
}
if (document.getElementById("uk").checked) {
const weight = Math.round(300 * 0.0714286) + ' stone';
const temperature = Math.round((94 - 32) * 5 / 9) + ' centigrade';
newStory = newStory.replace('94 fahrenheit', temperature);
newStory = newStory.replace('300 pounds', weight);
}
}
story.textContent = newStory;
story.style.visibility = 'visible';
}