简体   繁体   中英

Event listener not responding - Javascript

I am trying to write a quiz in pure javascript that loads new questions from an array and fills a table when the user clicks next. A seemingly simple problem I have is that I cannot get an event listener to work when the user clicks the next button. On JSFiddle it works, but it won't work on my end and I have no idea why. Just as a test I have it alerting if the button is pressed. I have also tested multiple different ways of checking if the document has loaded before executing to no avail.

HTML

<body>
    <table class="center">
        <tr>
            <th id='question' colspan="2">question</th>

            <td colspan="2"></td>
        </tr>
        <tr>
            <td id="answer0">Choice 1</td>
            <td><input id="radio0" type="radio" name=que_1 value="1" required/></td>
        </tr>
        <tr>
            <td id="answer1">choice 2</td>
            <td><input id="radio01" type="radio" name=que_1 value="1"/></td>
        </tr>
        <tr>
            <td id="answer2">choice 3</td>
            <td><input id="radio02" type="radio" name=que_1 value="1"/></td>
        </tr>
        <tr>
            <td id="answer3">choice 4</td>
            <td><input id="radio03" type="radio" name=que_1 value="1"/></td>
        </tr>

    </table>
    <div>
        <input type="button" id="next" value='Next'>
    </div>
</body>

Javscript

document.getElementById("next").addEventListener("click", function() {
    alert("works");
});

Thank you in advanced.

Make sure you bind the event handler after the DOM is loaded:

window.addEventListener('load', function() {
    document.getElementById("next").addEventListener("click", function() {
        alert("works");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM