无法从数组中删除元素

时间:2017-02-19 15:56:25

标签: javascript

几周前我开始自学JavaScript,遇到了一个我无法解决的问题。该程序的工作原理是允许用户输入保存在数组中的名称列表,并在屏幕上显示为li元素。然后程序将随机选择一个输入的人。尝试从列表中删除某个人时出现问题。我可以从HTML中删除它们,但不能从数组中删除它们。我试图使用如下所示的SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println("utc time: "+simpleDateFormat.format(cal.getTime())); 方法,但这只删除了数组中的最后一个元素。我认为这是因为.splice不适合这种用途,但不知道还有什么可以尝试。非常感谢任何帮助。

indexOf(li.value)

1 个答案:

答案 0 :(得分:0)

您的代码存在各种问题,有些是程序化的,有些是风格的,有些是您的逻辑。

您的主要问题是,具有value属性的唯一元素是表单元素。所以,当你写:

let i = students.indexOf(li.value);

您遇到问题,因为您将li设置为event.target的父节点。 event.target是启动事件的元素,在本例中为<button>,按钮的父级为<div>,其中(再次)没有value属性并且无论如何都不是正确的元素。

此值是您splice的基础。相反,您需要在li元素或数组列表中获取li的索引位置(它们应该相同)。

接下来,您首先不需要在此场景中使用数组,因为所有学生名称都是<ul>元素中的元素,这意味着可以通过“节点列表”是一个支持length属性的“类数组”对象,是可枚举和可索引的。将<li>元素内容保存在同步数组中不会在此处添加任何值,并使整个任务变得更加复杂,因为您必须使HTML列表与数组保持同步。

说完所有这些之后,这里有一个关于你正在尝试的工作的例子,注释内联解释为什么我的代码与你的代码不同。

// When the DOM is loaded and all elements are accessible...
window.addEventListener("DOMContentLoaded", function(){

  // Get references to the DOM elements needed to solve problem
  // Using "var" here is perfectly acceptable as their scope will
  // be the entire parent function, which is what we want. Get all
  // these references just once so we don't have to keep scanning
  // the DOM for them each time we want to work with the list.  Also,
  // name your variables "noun"-like names when they refer to elements
  var btnAdd = document.querySelector(".addStudent");
  var btnRandom = document.querySelector(".randomStudent");
  var list = document.getElementById("listStudentNames");
  var student = document.querySelector("input[type='text']");
  var output = document.querySelector(".report");
  
  // Set up an empty array to keep the synchronized student list in
  var students = [];

  // Set up click event handling functions
  btnAdd.addEventListener("click", addStudent);
  btnRandom.addEventListener("click", getRandomStudent);
  
  function addStudent(){
    // Make sure there was valid input
    if(student.value.trim() === ""){ return; }
  
    // Create a new <li> element
    var li = document.createElement("li");
    
    // Set new element up with a click event handler that will
    // cause the current element to be removed from the list
    li.addEventListener("click", removeStudent);
  
    // Populate the element with the text from the <input>
    // The element gets raw text set with the .textContent property
    // while content of form elements is gotten with the "value" 
    // property
    li.textContent = student.value;
    
    // Update the list id's to match the array indexes
    sync();
  
    // Add the element to the end of the <ul>'s list elements
    list.appendChild(li);
    
    // Add new student to the array:
    students.push(student.value);
    
    // Clear value from input
    student.value = "";
    
    logResults();
  }

  function getRandomStudent(){
    console.clear();
    
    if(students.length){
      // Use the built-in JavaScript Math object to get a random number
      // between 0 (inclusive) and 1 (exclusive) then multiply that
      // number by the lenght of the <li> node list to get a random
      // number between 0 and the amount of elements in the array
      var random = Math.floor(Math.random() * list.children.length);
      console.log("Random student is: " + list.children[random].textContent);
    } else {
      console.log("No students to choose from!");
    }
  }

  function removeStudent (evt){
  
    // Re-sync the indexes of the HTML elements to match the array
    sync();
  
    // Remove corresponding student from array first...
    console.clear();
    console.log("Student " + evt.target.id + " about to be removed");
    students.splice(+evt.target.id, 1);
  
    // Every event handling function automatically gets a reference
    // to the event that triggered the function sent into it. We can
    // access that event to get a reference to the actual DOM object
    // the caused the event to be triggered with "event.target"
    list.removeChild(evt.target); 
    
    logResults();
  }
  
  // We have to keep the HTML element indexes in sync with the array indexes
  function sync(){ 
    // Loop through the HTML elements and give them an id that corresponds
    // to the index position of its counterpart in the array.
    Array.prototype.forEach.call(list.children, function(el, index){
       el.id = index;
    });
  }
  
  // This is just a function for updating the display to show the contents
  // of the array to confirm that it is in sync with the list
  function logResults(){
    output.innerHTML = "Array now contains: <br>" + students.join("<br>");
  }

});
.list, .report { float:left; }
.report { background-color:aliceblue; }
<div class="list">
  <input type="text" class="studentName" placeholder="Enter Student Name Here">
  <button class="addStudent">Add student to list</button>  
  <ul id= "listStudentNames">
  </ul>
  <p class="description">(Click on a student to remove them from the list.)</p>
  <button class="randomStudent">Select a random student</button>
</div>
<div class="report"></div>