请问为什么这段代码在 onclick 事件后刷新我的页面

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

本文关键字:事件 onclick 刷新 我的 为什么 段代码 代码      更新时间:2023-09-26
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);
        }
    };
}

HTML 正文包括:

<!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>

代码输出新的列表元素,但会立即刷新。请帮忙。

您在表单标签中具有输入类型提交。提交按钮将表单发布到服务器。只需添加return false;即可阻止将表单发布到服务器。

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>

从您的 js 代码上方,无需使用表单标签。因为我们可以直接得到