[英]After a button is clicked/form submit, the CSS stylesheet doesn't appear
單擊使用按鈕后,我檢查頁面時的來源顯示 style.css 頁面消失,並且沒有應用 styles。 我不知道為什么會這樣。
我的 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 寫入文檔 stream 時,在關閉(加載)的文檔上調用 document.write 會自動調用 document.open,這將清除文檔。
如果您真的想使用document.write
,您需要將樣式表鏈接重寫到新文檔中。 但是最好只替換頁面上某些容器元素的 html,例如body
元素。
而不是使用覆蓋您的 html 的 document.write 您可以嘗試這種方法:
<input type="submit" value="Use" class="submit">
<!-- add new div to show the result -->
<div id="result"></div>
<script src="app.js"></script>
在點擊事件中:
useBtn.addEventListener('click', function(){
let person = document.querySelector('.fname').value;
let res = document.getElementById('result');
res.innerHTML = "<h2>It's "+person+"'s turn!</h2>";
// add further information to innerHTML here
// hide input fname and submit button
redoBtn();
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.