使用html和javascript的表单向容器添加新项



我目前正在尝试使用表单输入添加网格项到网格容器。如果有人有任何建议,那将非常有帮助。

这是我到目前为止的代码:

<!DOCTYPE html>
<html>
<head>
<script>
function addNote(note) {
childNumber = 1;
let noteContainer = document.getElementById("grid-container");
var newNote = '<p>Child' + note + childNumber + '</p>';
noteContainer.insertAdjacentHTML("test", newNote)
childNumber++;
}
</script>
</head>
<body>
<style>
#note {
height: 200px;
font-size: 14pt;
}

.grid-container {
display: grid;
grid-template-rows: repeat(1, [row] auto);
grid-template-columns: repeat(4, 1fr);
padding: 10px;
}

.grid-item {
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
</style>

<div class="grid-container">
<div class="grid-item"></div>

</div>
<div>
<h2>Notes</h2>
<form>
<label for="Note">Add Note</label><br>
<input type="text" id="note" name="Note"><br>
<button onclick="addNote(note)">Submit</button>
</form>
</div>
</body>
</html>

如果你有一个表单,使用submit事件并阻止它提交

如果没有,使用type="button">

也没有使用注释

的值我建议你把注释包在div中,然后把HTML附加到容器

let childNumber = 0;
const noteContainer = document.getElementById("grid-container");
const note =  document.getElementById("note");
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop the submission
var newNote = '<div class="grid-item"><p>Child ' + note.value + childNumber + '</p></div>';
noteContainer.innerHTML += newNote
childNumber++;
})
#note {
height: 200px;
font-size: 14pt;
}
.grid-container {
display: grid;
grid-template-rows: repeat(1, [row] auto);
grid-template-columns: repeat(4, 1fr);
padding: 10px;
}
.grid-item {
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
<div id="grid-container">

</div>
<div>
<h2>Notes</h2>
<form id="myForm">
<label for="Note">Add Note</label><br>
<input type="text" id="note" name="Note"><br>
<button>Submit</button>
</form>
</div>

最新更新