简体   繁体   中英

Please why does this code refresh my page after the onclick event?

window.onload = init;

function init() {
    var button = document.getElementById("addButton");
    button.onclick = function () {
        var songTitle = document.getElementById("songTextInput").value;
        if (songTitle == "") alert("Baba Put Something Jare");
        else {
            var playlist = document.getElementById("playlist");
            var song = document.createElement("li");
            song.innerHTML = songTitle;
            playlist.appendChild(song);
        }
    };
}

The HTML body consist of :

 <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="#" /> <meta charset="UTF-8" /> <title>Web Tunes</title> <script src="playlist.js"></script> </head> <body> <form> <input type="text" id="songTextInput" placeholder="Song Title"> <input type="submit" id="addButton" value="Add Song"> </form> <ul id="playlist"></ul> </body> </html> 

The code outputs the new list element but refreshes immediately.. Please help.

You have an input type submit inside a form tag. A submit button posts the form to the server. Just add return false; to stop the form from being posted to the server.

window.onload = init;

function init() {
    var button = document.getElementById("addButton");
    button.onclick = function () {
        var songTitle = document.getElementById("songTextInput").value;
        if (songTitle == "") alert("Baba Put Something Jare");
        else {
            var playlist = document.getElementById("playlist");
            var song = document.createElement("li");
            song.innerHTML = songTitle;
            playlist.appendChild(song);
        }
        return false;
    };
}
<!doctype html>
<html lang="en">

<head>
  <link rel="stylesheet" href="#" />
  <meta charset="UTF-8" />
  <title>Web Tunes</title>
  <script src="playlist.js"></script>
</head>

<body>

    <input type="text" id="songTextInput" placeholder="Song Title">
    <input type="submit" id="addButton" value="Add Song">

  <ul id="playlist"></ul>
</body>

</html>

From above your js code, no need to use the form tag . Because we can get directly

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