无法获取 javascript 来修改标头

问题描述 投票:0回答:1

此代码应该要求用户输入并根据提交的字符串返回错误或正确的结果(正确答案是“Aconcagua”)。运行它并提交时,这些答案都不会打印到屏幕上。我对 javascript 和 HTML 还很陌生。

<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="styles.css" rel="stylesheet">
        <title>Trivia!</title>
        <script>

            function wrong2()
            {
                document.querySelector('#2solution').innerHTML = "Incorrect.";
                document.querySelector('#input').style.backgrounColor = 'red';
            }
            function right2()
            {
                document.querySelector('#2solution').innerHTML = "Correct!";
                document.querySelector('#input').style.backgrounColor = 'green';
            }

            a = "Aconcagua";
            document.querySelector('#form').addEventListener('submit', function(event){
                if (document.querySelector('#input').value.localeCompare(a) == 0)
                {
                    right2;
                }
                else
                {
                    wrong2;
                }

                event.preventDefault();
            });
        </script>
    </head>
    <body>
        <div class="header">
            <h1>Trivia!</h1>
        </div>

            <div class="section">
                <h2>Part 2: Free Response</h2>
                <hr>
                <h3>What is the highest mountain in South America?</h3>
                <form action="" id="form">
                    <input id="input" type="text">
                    <button id="b" type="sumbit">Submit</button>
                </form>
            </div>
            <h2 id="2solution"></h2>
        </div>
    </body>
</html>

javascript html css forms submit
1个回答
0
投票

您缺少调用函数所需的括号 ()。对2()和错2()。 如果没有 (),它们只是被视为对函数的引用而不是函数调用。

更正代码:

<script>
    function wrong2() {
        document.querySelector('#2solution').innerHTML = "Incorrect.";
        document.querySelector('#input').style.backgroundColor = 'red';
    }

    function right2() {
        document.querySelector('#2solution').innerHTML = "Correct!";
        document.querySelector('#input').style.backgroundColor = 'green';
    }

    // Function for event listener
    function setUpEventListener() {
        a = "Aconcagua";
        document.querySelector('#form').addEventListener('submit', function (event) {
            if (document.querySelector('#input').value.localeCompare(a) == 0) {
                right2(); 
            } else {
                wrong2(); 
            }
            event.preventDefault();
        });
    }

    // Ensure the event listener is set up after the form element exists
    document.addEventListener("DOMContentLoaded", function () {
        setUpEventListener();
    });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.