单击按钮/提交表单后,CSS样式表不出现

时间:2020-06-17 13:28:41

标签: javascript html 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;
    })
}

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您的document.write将覆盖您的所有html,包括链接的样式表。

来自https://developer.mozilla.org/en-US/docs/Web/API/Document/write

注意:当document.write写入文档流时,在关闭的(已加载)文档上调用document.write会自动调用document.open,这将清除文档。

如果您确实要使用document.write,则需要将样式表链接重写到新文档中。但是,最好替换页面上某些容器元素的html,例如body元素。

答案 1 :(得分:0)

您可以尝试以下方法,而不是使用document.write来覆盖您的html:

    <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();

})
相关问题