【问题标题】:How to add and remove items from array with a text input field如何使用文本输入字段从数组中添加和删除项目
【发布时间】:2021-09-15 18:36:12
【问题描述】:

我正在尝试制作一个简单的购物清单程序。有一个添加项目和一个删除项目按钮。还有一个文本框。例如,当您在文本字段中输入“apples”并点击添加按钮时。然后添加按钮应将“apples”放入groceryList 数组中,然后在标有groceryinfo 的div 区域中显示苹果。

删除按钮也不起作用。例如,如果在文本字段中输入的值是“苹果”,则列表中有五个不同的项目。应该找到苹果,然后将其取出。然后,groceryList 数组应重新显示并显示该数组包含不包含已删除项目的内容。

<body>
    My grocery list
    <br>
    <br>
    <div id="groceryinfo"></div>
    <br>
    <br>
    <input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
    <br>
    <input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
    <script>
        var groceryList = [];
        var groceryitem;
        var description;
        description = document.getElementById("groceryinfo");

        function Add() {
            groceryitem = document.getElementById('Text1').value;
            groceryList.push(groceryitem);
            groceryList = description;
            
        }

        function Remove() {
            for (var i = 0; i <= groceryList.length; i++) {
                if (groceryList[i] == groceryitem) groceryList.splice(i, 1);
                groceryList = description;
            }
        }
    </script>

【问题讨论】:

  • 我认为您需要执行description.innerHTML = groceryList.toString() 之类的操作才能使groceryinfo div 真正更新。
  • Add 函数的最后一行中,您将groceryList 从数组转换为元素,从而使Remove 函数失败。我想你想要description.innerText = groceryList.toString();

标签: javascript html


【解决方案1】:

您可以使用document.getElementById("groceryinfo").innerHTML 实现此目的,如下所示:

<body>
    My grocery list
    <br>
    <br>
    <div id="groceryinfo"></div>
    <br>
    <br>
    <input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
    <br>
    <input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
    <script>
        var groceryList = [];
        var groceryitem;
        var description;
        description = document.getElementById("groceryinfo");

        function Add() {
            groceryitem = document.getElementById('Text1').value;
            groceryList.push(groceryitem);
            document.getElementById("groceryinfo").innerHTML = groceryList.toString();
        }

        function Remove() {
            for (var i = 0; i <= groceryList.length; i++) {
                if (groceryList[i] === groceryitem) {
                    groceryList.splice(i, 1);
                    document.getElementById("groceryinfo").innerHTML = groceryList.toString();
                } 
            }
        }
    </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 2021-10-03
    • 1970-01-01
    • 2022-09-25
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多