javascript - 单击按钮/表单提交后,CSS样式表不出现
问题描述
单击使用按钮后,我检查页面时的来源显示 style.css 页面消失了,并且没有应用任何样式。我无法弄清楚为什么会这样。
我的 index.html 页面如下所示:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500&family=Roboto:wght@100;300;400;700&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="First name" class="fname">
<input type="submit" value="Use" class="submit">
<script src="app.js"></script>
</body>
</html>
我的 app.js 是这样的:
const useBtn = document.querySelector('.submit');
const reloadBtn = document.querySelector('.btn__reload')
document.body.style.fontFamily = "Roboto;"
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
document.write(`<h2>It's ${person}'s turn!</h2>`)
document.write(`<h4>How long will they live?</h4>`)
let oldAge = `<p>${Math.floor((Math.random() * 10)+ 30)}</p>`
document.write(oldAge)
document.write(`<h4>What will be their yearly salary?</h4>`)
let salary = `<p>${Math.floor(Math.random() * 10000)}</p>`
document.write(salary)
document.write(`<h4>What will be their career</h4>`)
const jobs = [ 'plumber', 'doctor', 'witch', 'president', 'trump supporter']
let job = Math.floor(Math.random() * jobs.length)
document.write(jobs[job])
redoBtn();
})
function redoBtn(){
let tryAgain = document.createElement('button')
document.body.appendChild(tryAgain)
let buttonText = document.createTextNode('Try Again')
tryAgain.appendChild(buttonText)
tryAgain.addEventListener('click', function(){
window.location.href = window.location.href;
})
}
任何帮助都非常感谢!
解决方案
您document.write
正在覆盖您的所有 html,包括您的链接样式表。
来自https://developer.mozilla.org/en-US/docs/Web/API/Document/write:
注意:当 document.write 写入文档流时,在关闭(加载)的文档上调用 document.write 会自动调用 document.open,这将清除文档。
如果您真的想使用document.write
,则需要将样式表链接重写到新文档中。但是最好只替换页面上某些容器元素的 html,例如body
元素。
推荐阅读
- c# - 使用来自多个线程的引用类型写入数组
- php - Laravel Livewire not persisting data in array when updating
- svg - 如何更新 Mapel SVG 地图中特定国家的背景颜色?
- python - 设置 matplotlib 视频动画大小 (1920x1080)
- android - SimpleDateFormat 表示还有 2 个小时
- c++ - 我在视觉工作室中收到错误 LNK1181,我应该如何解决这个问题?
- ios - 使用格式参数时,Swift 中的字符串初始值设定项问题
- python - 展平 numpy 数组并保留索引值
- python - 仅在 Python subprocess.Popen.communicate 中发送标准输入后获取标准输出
- oracle - Oracle 段的范围不相等?