Как редактировать списки из пользовательского ввода на HTML-странице - PullRequest
0 голосов
/ 22 марта 2019

Я сделал код в HTML с помощью других, который будет оценивать список из пользовательского ввода с несколькими функциями.Код теперь будет отслеживать сумму всех чисел в списке, среднее, максимальное, минимальное и частоту чисел.Последнее, что я хочу, чтобы код был в состоянии сделать, это иметь возможность удалять элементы из списка.Например, если пользователь вводит 1,2,3,4,5 и хочет избавиться от 3, он может нажать кнопку и 3 будет удален из списка.Я не совсем уверен, как это сделать, поэтому было бы полезно получить некоторую помощь в выяснении этого.

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>

<head>

  <link rel="stylesheet" type="text/css" href="style.css">

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- This only allows the user to input numbers --->

  <input type='number' id='input'>

  <!--- This is the button that adds the number to the list --->

  <input type='button' value='add to list' id='add' disabled="disabled">

  <!--- Here we have a title for the list --->

  <div class="title">Topics</div>

  <!--- This will list all of the numbers --->

  <ul id='list'></ul>

  <!--- When clicked, this buttons alert the user with the numbers --->

  <button id="sum"> Sum </button>
  <button id="max"> Max </button>
  <button id="min"> Min </button>
  <button id="avg"> Avg </button>
  <button id="frequency"> Frequency </button>

  <p><button onclick="lowHigh()">Sort</button></p>


  <div>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

  </div>
  
  <script>
    
    let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);

// This will add the input number to the list and clear the input

function addClick() {
  var li = document.createElement("li");
  li.textContent = input.value;
  list.appendChild(li);
  update(input.value);
  input.value = "";
  add.disabled = "disabled";

}

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable() {
  if (this.value === "") {
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update(enteredValue) {
  frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.textContent;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');

  alert(text);
}

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}

function avgClick() {
  alert("The average of your numbers is: " + avg);
}

function minClick() {
  alert("The smaller number is: " + min);
}

function maxClick() {
  alert("The greater number is: " + max);
}

function lowHigh() {
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("list");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    b = list.getElementsByTagName("li");
 
    // Loop through all list items:
    for (i = 0; i < (b.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Check if the next item should
      switch place with the current item: */
      if (b[i].innerText > b[i + 1].innerText) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }


}

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
    
    
  </script>   


</body>
  

  
  
</html>

1 Ответ

2 голосов
/ 22 марта 2019

Сначала я изменил функцию addClick(). Я добавил новую кнопку к каждому элементу списка вместе с событием onclick, прикрепленным к кнопке, которая просто удаляет родительский элемент (<li>). Кроме того, я обернул значение списка в <span>. Теперь это должно хорошо служить вашей цели. Каждая строка, которую я изменил, получила комментарий в приведенном ниже коде, чтобы вы получили общее представление о том, что я сделал / изменил и почему.

function addClick() {
  var li = document.createElement("li");
  var button = document.createElement("button"); //create new button
  var span = document.createElement("span"); //create span which is wrapped around value
  button.onclick = function() { //add onclick event to button
     this.parentNode.remove(this.parentNode); //remove <li> node
     update(this.parentNode.firstChild.innerHTML, true); //update values e.g. frequency, sum, avg
  };
  button.innerHTML = "remove"; //give button a text
  list.appendChild(li);
  span.textContent = input.value; //the value is now added to span
  li.appendChild(span); //add span to li
  li.appendChild(button); //add button to li
  update(input.value);
  input.value = "";
  add.disabled = "disabled";
}

Я также изменил функцию update() и изменил параметры функции (подпись), чтобы различать удаление и добавление элементов. Кроме того, я добавил некоторый код для настройки счетчика frequency в случае удаления. Также было необходимо delete элемент из frequency, если count = 0. Наконец, строка, которая извлекает значение одного элемента списка для арифметических операций, была исправлена, потому что DOM изменился, поскольку есть новый <span> и <button> элемент в каждом <li>.

function update(enteredValue, remove) { //add parameter to know when a frequency should be removed
  if(remove){ // remove frequency
    frequency[enteredValue] = frequency[enteredValue] - 1; //substract by one
    if(frequency[enteredValue] == 0) //if frequency = 0
      delete frequency[enteredValue]; //delete the element
  }else{
    frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  }

  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.firstChild.innerHTML; //now retrieve the value from the first child (<span>)
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

Ваш элемент списка теперь после создания выглядит следующим образом:

<li><span>VALUE</span><button>Remove</button></li>

Обновление: изначально я что-то упустил, мой код не учитывал частотную переменную, которая изменяется каждый раз при добавлении элемента. Я исправил проблему сейчас и изменил / расширил свое объяснение. Теперь частота также корректна при удалении элементов.


Полный код здесь:

.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>

<html>

<head>

  <link rel="stylesheet" type="text/css" href="style.css">

</head>


<body>

  <link rel="stylesheet" type="text/css" href="style.css">
  <!--- This only allows the user to input numbers --->

  <input type='number' id='input'>

  <!--- This is the button that adds the number to the list --->

  <input type='button' value='add to list' id='add' disabled="disabled">

  <!--- Here we have a title for the list --->

  <div class="title">Topics</div>

  <!--- This will list all of the numbers --->

  <ul id='list'></ul>

  <!--- When clicked, this buttons alert the user with the numbers --->

  <button id="sum"> Sum </button>
  <button id="max"> Max </button>
  <button id="min"> Min </button>
  <button id="avg"> Avg </button>
  <button id="frequency"> Frequency </button>

  <p><button onclick="lowHigh()">Sort</button></p>


  <div>

    <button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>

  </div>
  
  <script>
    
    let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);

// This will add the input number to the list and clear the input
function addClick() {
  var li = document.createElement("li");
  var button = document.createElement("button");
  var span = document.createElement("span");
  button.onclick = function() { this.parentNode.remove(this.parentNode); update(this.parentNode.firstChild.innerHTML, true); };
  button.innerHTML = "remove";
  list.appendChild(li);
  span.textContent = input.value;
  li.appendChild(span);
  li.appendChild(button);
  update(input.value);
  input.value = "";
  add.disabled = "disabled";
}

function removeElement(){
  alert("test");
}

// This allows the "add to list" button to be turned on/off depending if the user has typed in a number

function enableDisable() {
  if (this.value === "") {
    add.disabled = "disabled";
  } else {
    add.removeAttribute("disabled");
  }
}

// This will calculate and update all variable values

function update(enteredValue, remove) {
  if(remove){
    frequency[enteredValue] = frequency[enteredValue] - 1;
    if(frequency[enteredValue] == 0)
      delete frequency[enteredValue];
  }else{
    frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
  }

  sum = 0;
  min = Infinity;
  max = -Infinity;
  var count = 0;
  for (var i of list.children) {
    let val = +i.firstChild.innerHTML;
    sum += val;
    if (val > max) max = val;
    if (val < min) min = val;
    count++;
  }
  avg = sum / count;
}

function frequencyClick() {
  let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
    return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
  }, []).join('\n');

  alert(text);
}

// This functions will alert the numbers

function sumClick() {
  alert("The sum of your numbers is: " + sum);
}

function avgClick() {
  alert("The average of your numbers is: " + avg);
}

function minClick() {
  alert("The smaller number is: " + min);
}

function maxClick() {
  alert("The greater number is: " + max);
}

function lowHigh() {
  var list, i, switching, b, shouldSwitch;
  list = document.getElementById("list");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    b = list.getElementsByTagName("li");
 
    // Loop through all list items:
    for (i = 0; i < (b.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Check if the next item should
      switch place with the current item: */
      if (b[i].innerText > b[i + 1].innerText) {
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark the switch as done: */
      b[i].parentNode.insertBefore(b[i + 1], b[i]);
      switching = true;
    }
  }


}

// Here we add all events

input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
    
    
  </script>   


</body>
  

  
  
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...