h08.14 2024-05-24 20:34 采纳率: 50%
浏览 10

服务器启动html文件时 js脚本没有反应

关于服务器server.js启动html文件时 js脚本没有反应
如下代码 逻辑应该在点击start按钮后隐藏元素和显示元素但是并没有

这是Quit.html
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Quit</title>
    <link rel="stylesheet" href="style.css">


</head>

<body>

<header>

    <h1>MyWebsite</h1>
    <img src="./img/school_logo.png" alt="school logo">

    <nav>
        <ul>

            <li><a href="IntroductionPage.html">Home</a></li>
            <li><a href="AboutPage.html">About me</a>
                <div class="submenu">
                    <a href="#Interest">My Interest</a>
                    <a href="#Major">My Major</a>
                    <a href="#Resume">My Resume</a>
                </div>
            </li>
            <li><a href="Quit.html">Quiz</a></li>

        </ul>
    </nav>
</header>
<main>
    <article>
        <div id="div1">
            <h2>Welcome to quiz!</h2>
            <label for="welcome">Give your name: </label>
            <input type="text"  id="welcome" name="welcome" required minlength="4" maxlength="8" size="10" />
            <button type="button"  onclick="show(); renewal()" id="btn1">start</button>
        </div>
        <div id="div2" style="display: none">
            <h2 id="questionNo">Question</h2>
            <label for="welcome" id="questionText"> ? </label>
            <button type="button"  onclick="selectionAnswer('A')" id="btn2">A</button>
            <button type="button"  onclick="selectionAnswer('B')" id="btn3">B</button>
            <button type="button"  onclick="selectionAnswer('C')" id="btn4">C</button>
            <button type="button"  onclick="selectionAnswer('D')" id="btn5">D</button>
            <label id="timer">Time to answer: 15 seconds</label>
        </div>

        <div id="div3" style="display: none">
            <h2 >Your answer is correct!</h2>
            <button type="button"  onclick="renewal()" id="btn6">Next question</button>
        </div>

        <div id="div4" style="display: none">
            <h2>Your answer is incorrect!</h2>
            <button type="button"  onclick="renewal()" id="btn7">Next question</button>
        </div>

        <div id="div5" style="display: none">
            <h2>You completed all the questions!</h2>
            <label id="CorrectAnswer">You got 2 right out of 10.</label>
            <label id="timeAnswered"></label>
            <label id="output"></label>
        </div>



    </article>
</main>
<script src ="/socket.io/socket.io.js"></script>
<script src="public/quit.js"> </script>
<footer>
    <p><a href="https://blog.csdn.net/weixin_74400487">My Blog</a> by Zheng Zihao.</p>
</footer>

</body>
</html>

这是server.js
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();

const server = http.createServer(app);

const io = socketIO(server);

const port = 3000;
app.use(express.static('public'));

let initialRanking = [];



const correctAnswers = {
    1: "Mars",
    2: "Canberra",
    3: "Leonardo da Vinci",
    4: "Pacific Ocean",
    5: "Avocado",
    6: "Jane Austen",
    7: "China",
    8: "Blue whale",
    9: "Brasília",
    10: "Alexander Fleming"
}

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/Quit.html');
});

app.get('/AboutPage.html', (req, res) => {
    res.sendFile(__dirname +'/About page.html');
});

app.get('/IntroductionPage.html', (req, res) => {
    res.sendFile(__dirname +'/IntroductionPage.html');
});

app.get('/Quit.html', (req, res) => {
    res.sendFile(__dirname +'/Quit.html');
});


io.on('connection', (socket) => {
    console.log('A user connected');
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
    socket.on('sendUsername', (inputName) => {
        console.log(`userName:${inputName}`);

    });
    socket.on('submitAnswer', (data) => {
        const {question,answer,time } = data;
        const isCorrect = correctAnswers[question] === answer;

        socket.emit('answerResult', {
            isCorrect: isCorrect,
            correctAnswer: correctAnswers[question]
        });
    });





    function updateRanking(rank, newUser) {
        // Add the new user to the leaderboard array
        rank.push(newUser);

        // bubble sort algorithm to update the leaderboard
        for (let i = 0; i < rank.length - 1; i++) {
            for (let j = 0; j < rank.length - i - 1; j++) {
                if (rank[j].correctCount < rank[j + 1].correctCount) {
                    [rank[j], rank[j + 1]] = [rank[j + 1], rank[j]];
                } else if (rank[j].correctCount === rank[j + 1].correctCount) {
                    if (rank[j].totalTime > rank[j + 1].totalTime) {
                        [rank[j], rank[j + 1]] = [rank[j + 1], rank[j]];
                    }
                }
            }
        }

        return rank;
    }
    socket.on('finish', (data) => {
        const { CorrectAnswer: CorrectAnswer,
            userName: inputName,
            time : timeAnswered } = data;

        const newUser = { username: inputName, correctCount: CorrectAnswer, totalTime: timeAnswered };
        const updatedRanking = updateRanking(initialRanking, newUser);

        socket.emit('rankresult', {
            initialRanking:initialRanking
        });

    });
});



app.listen(port, () => {
    console.log(`Server running at https://indexmatrix-journalclone-3000.codio-box.uk/AboutPage.html`)
});

这是quit.js
 var questions = [
        {
            question: "Which planet is known as the Red Planet?",
            options: ["Jupiter", "Mars", "Venus", "Saturn"],
        },
        {
            question: "What is the capital of Australia?",
            options: ["Sydney", "Melbourne", "Canberra", "Brisbane"],
        },
        {
            question: "Who painted the Mona Lisa?",
            options: ["Leonardo da Vinci", "Pablo Picasso", "Vincent van Gogh", "Michelangelo"],
        },
        {
            question: "What is the largest ocean on Earth?",
            options: ["Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"],
        },
        {
            question: "What is the main ingredient in guacamole?",
            options: ["Tomato", "Avocado", "Onion", "Pepper"],
        },
        {
            question: "Who wrote 'Pride and Prejudice'?",
            options: ["Emily Bronte", "Jane Austen", "Charlotte Bronte", "Louisa May Alcott"],
        },
        {
            question: "Which country is famous for the Great Wall?",
            options: ["Japan", "China", "India", "Russia"],
        },
        {
            question: "What is the largest mammal?",
            options: ["Elephant", "Blue whale", "Giraffe", "Hippopotamus"],
        },
        {
            question: "What is the capital of Brazil?",
            options: ["Rio de Janeiro", "Brasília", "São Paulo", "Salvador"],
        },
        {
            question: "Who discovered penicillin?",
            options: ["Alexander Fleming", "Marie Curie", "Louis Pasteur", "Robert Koch"],
        }
    ];
    var startTime;

    function startDate() {
        startTime = new Date();
    }

    var endTime;

    function endDate() {
        endTime = new Date();
    }

    var socket = io();

    var inputName = '';

    function show() {
        let div1obj = document.getElementById("div1");
        let div2obj = document.getElementById("div2");
        inputName = document.getElementById("welcome").value;
        socket.emit('sendUsername', inputName);
        div1obj.style.display = "none";
        div2obj.style.display = "block";
        startDate()
    }

    function startTimer() {

        let timeLeft = 15; // 初始倒计时时间,单位为秒
        document.getElementById("timer").innerText = "Time to answer: " + timeLeft + " seconds"; // 更新显示的倒计时时间

        let timerInterval = setInterval(function () {
            timeLeft--; // 每次执行时减少一秒

            document.getElementById("timer").innerText = "Time to answer: " + timeLeft + " seconds"; // 更新显示的倒计时时间
            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                if (!selectionAnswer) {
                    selectionAnswer('F')
                }
            }
            if (selectionAnswer) {
                clearInterval(timerInterval);
            }


        }, 1000); // 每隔一秒执行一次

    }

    var questionNo = 1;

    function renewal() {
        let div2obj = document.getElementById("div2");
        let div3obj = document.getElementById("div3");
        let div4obj = document.getElementById("div4");
        div3obj.style.display = "none";
        div4obj.style.display = "none";
        div2obj.style.display = "block";
        document.getElementById("questionNo").innerText = 'Question' + questionNo;
        document.getElementById("questionText").innerText = questions[questionNo - 1].question;
        document.getElementById("btn2").innerText = 'A.' + questions[questionNo - 1].options[0];
        document.getElementById("btn3").innerText = 'B.' + questions[questionNo - 1].options[1];
        document.getElementById("btn4").innerText = 'C.' + questions[questionNo - 1].options[2];
        document.getElementById("btn5").innerText = 'D.' + questions[questionNo - 1].options[3];
        startTimer();

    }

    var selectedAnswer = '';

    function selectionAnswer(selection) {

        selectedAnswer = selection;

        socket.emit('submitAnswer', {
            question: questionNo,
            answer: selectedAnswer,
        });
        judgeAnswer();
        questionNo = questionNo + 1;
    }


    var CorrectAnswer = 0;

    function judgeAnswer() {
        let div2obj = document.getElementById("div2");
        let div3obj = document.getElementById("div3");
        let div4obj = document.getElementById("div4");
        let div5obj = document.getElementById("div5");
        div2obj.style.display = "none";

        socket.on('answerResult', (data) => {
            const {isCorrect, correctAnswer} = data;
            canswer = correctAnswer;
            if (isCorrect) {
                div3obj.style.display = "block";
                CorrectAnswer = CorrectAnswer + 1;
            } else {
                div4obj.style.display = "block";
            }

            socket.off('answerResult');
        });

        if (questionNo == 10) {
            document.getElementById("btn6").style.display = "none";
            document.getElementById("btn7").style.display = "none";
            div5obj.style.display = "block";
            document.getElementById("CorrectAnswer").innerText = "You got " + CorrectAnswer + " right out of 10.";
            endDate();
            var timeAnswered = (endTime - startTime) / 1000;
            document.getElementById("timeAnswered").innerText = inputName + ' you use ' + timeAnswered + ' seconds to finish.';
            socket.emit('finish', {
                CorrectAnswer: CorrectAnswer,
                userName: inputName,
                time: timeAnswered
            });
            socket.on('rankresult', (data) => {
                const {initialRanking} = data;
                createRankingList(initialRanking);


            });
        }
    }

    function createRankingList(rankingData) {
        //page display
        const rankingList = document.getElementById('output');
        const li = document.createElement('li');
        // create ranking list
        rankingData.forEach((user, index) => {
            li.textContent = `${index + 1}  -  ${user.username} -- correct answers: ${user.correctCount} -- use time:${user.totalTime}`;
            rankingList.appendChild(li);

        });
    }

  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2024-05-24 20:35
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    根据你提供的代码和描述,这里有几个可能的原因导致JavaScript脚本没有按预期执行:

    1. 脚本加载顺序问题:在HTML文件中,quit.js 脚本是通过 <script src="public/quit.js"> </script> 引入的,但是没有指定 defer 属性。这意味着脚本会在解析HTML时立即加载和执行,如果DOM元素还没有完全加载,脚本中的DOM操作可能会失败。可以通过添加 defer 属性来解决这个问题,如下所示:

      <script src="public/quit.js" defer></script>
      
    2. 路径问题server.js 中使用了 app.use(express.static('public')); 来提供静态文件服务,这意味着 public 文件夹下的所有内容都可以被访问。确保 quit.js 文件位于 public 文件夹内,并且路径正确。

    3. 函数定义问题:在 quit.js 中,show() 函数被定义了,但是在HTML中按钮的 onclick 属性调用了 show(); renewal(),但是 renewal() 函数在 show() 函数之前并没有定义。这可能导致 renewal() 函数未定义的错误。确保 renewal() 函数在调用之前已经定义。

    4. 浏览器控制台错误:检查浏览器的开发者工具控制台,查看是否有任何JavaScript错误。这些错误可能会阻止脚本的执行。

    5. 事件监听器问题:在 quit.js 中,judgeAnswer 函数中使用了 socket.on('answerResult', ...) 来监听服务器的响应。但是,这个监听器是在 judgeAnswer 函数内部定义的,这意味着每次调用 judgeAnswer 时都会添加一个新的监听器。这可能导致预期之外的行为。考虑将监听器移出 judgeAnswer 函数,或者在不需要时使用 socket.off('answerResult') 来移除监听器。

    6. 异步问题:由于使用了socket.io进行通信,确保服务器和客户端之间的连接是开放的,并且服务器能够正确处理和响应客户端的事件。

    7. 按钮点击事件:确保按钮的 onclick 事件没有被阻止。有时候,如果按钮或其父元素上有 event.preventDefault() 调用,可能会阻止默认行为。

    请根据这些建议检查你的代码,并进行相应的调整。如果问题仍然存在,建议逐步调试JavaScript代码,确保每个函数都能按预期执行。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月24日

悬赏问题

  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件