私は数週間前に自分自身でJavaScriptを自己学習し始め、解決できない問題に遭遇しました。このプログラムは、ユーザーが配列に保存された名前のリストを入力できるようにすることによって機能し、画面上にli要素としても表示されます。プログラムはランダムに入力された人の1人を選択します。私の問題は、リストから人を削除しようとしたときに発生します。 HTMLからは削除できますが、配列からは削除できません。私は以下のように.splice
メソッドを使用しようとしましたが、これは配列の最後の要素だけを削除します。私はこれがindexOf(li.value)
には適していないと考えていますが、他に何を試していいのかわかりません。どんな助けも大歓迎です。配列から要素を削除する際の問題
<!DOCTYPE html>
<html>
<head>
<title>Student Randomiser</title>
<link rel="stylesheet" href="custom.css">
</head>
<body>
<h1 id="myHeading">Student Randomiser</h1>
<div class="list">
<p class="description">Add Students:</p>
<input type="text" class="studentName" value="Write Students Here">
<button class="addStudent">Add student</button>
<ul id= "listStudentNames">
</ul>
<button class="randomStudent">Select a random student</button>
</div>
<script src="randomNamePicker.js"></script>
</body>
</html>
const addStudent = document.querySelector('button.addStudent');
const studentName = document.querySelector('input.studentName');
const randomStudent = document.querySelector('button.randomStudent');
const listStudentNames = document.querySelector("ul");
let students = [
]
let number
window.onload=function(){
addStudent.addEventListener('click', addStudentToList);
randomStudent.addEventListener('click', selectRandomStudent);
listStudentNames.addEventListener("click", removeStudent);
}
function addButtons(li){
let remove =document.createElement('button');
remove.className= "removeStudent";
remove.textContent = "Remove Student";
li.appendChild(remove)
}
function removeStudent(){
if (event.target.tagName === "BUTTON") {
let li = event.target.parentNode;
let ul = li.parentNode;
let i = students.indexOf(li.value);
students.splice(i,1);
ul.removeChild(li);
}}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
number = Math.floor(Math.random() * (max - min)) + min;
}
function addStudentToList() {
students.push(studentName.value);
var ul = document.getElementById("listStudentNames");
var li = document.createElement("li");
li.appendChild(document.createTextNode(studentName.value));
addButtons(li);
ul.appendChild(li);
studentName.value = "";
}
function selectRandomStudent(){
getRandomIntInclusive(0, students.length);
alert(students[number]);
}
あなたがそれをデバッグがありますか?コンソールにエラーがありますか? 'i'の値は何ですか? – Carcigenicate
機能が呼び出されていますか?ボタンクリックイベントでイベントリスナーがありますか?もしそうなら、私はここにそれらを追加することをお勧めします。また、コードのどの部分がコメントを介してどのファイルに属しているかを文書化すると便利です。 –
@MikeLawsonコンソールエラーはありません。私はコード全体を添付していますので、理解しやすくなることを願っています。私が言いましたように、混乱している場合はお詫びします。私はちょうどこれをまとめることが私にとって挑戦でした。 –