[英]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 : 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>
The code outputs the new list element but refreshes immediately.. Please help. 该代码输出新的列表元素,但立即刷新。
You have an input type submit inside a form tag. 您在表单标签中有一个输入类型Submit 。 A submit button posts the form to the server. 提交按钮帖子的形式向服务器。 Just add return false;
只需添加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 . 从您的js代码上方,无需使用form标签 。 Because we can get directly 因为我们可以直接得到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.