gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:11:01 28 4
gpt4 key购买 nike

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;
};
}

关于javascript - 请问为什么这段代码会在 onclick 事件后刷新我的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598195/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com