我在其他人的帮助下用 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>
最佳答案
首先我修改了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
的元素如果计数 = 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>
关于javascript - 如何根据 HTML 页面中的用户输入编辑列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292386/