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>
代码输出新的列表元素但立即刷新..请帮助。
答案 0 :(得分:1)
您在表单标记中有输入类型提交。提交按钮将表单发布到服务器。只需添加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;
};
}
答案 1 :(得分:0)
<!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代码上方,无需使用 表单标记 。 因为我们可以直接获得