几个星期前,我开始自学自学JavaScript,并遇到了一个我无法解决的问题。该程序通过允许用户输入保存在数组中并且也在屏幕上显示为li元素的名称列表起作用。然后该程序将随机选择一个输入的人。尝试从列表中删除某人时出现问题。我能够从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]);
}
你有没有调试呢?有没有控制台错误? “我”的价值是什么? – Carcigenicate
你确定你的功能正在引发吗?你有没有关于按钮点击事件的事件监听器?如果是这样,我会建议在这里添加它们。另外,通过注释来记录代码的哪些部分属于哪些文件会很有帮助。 –
@MikeLawson无控制台错误。我附上了整个代码,希望能够更容易理解。道歉,如果它是一团糟,正如我刚才提到的,我刚刚开始,所以把它放在一起对我来说是一个挑战。 –