【问题标题】:My input string values will not display on my list我的输入字符串值不会显示在我的列表中
【发布时间】:2020-03-05 15:04:27
【问题描述】:

我想要显示数组的项目。单击按钮时,我需要执行以下操作:

  • 在显示数组的开头、结尾或中间添加一个元素
  • 对数组进行排序
  • 从数组中删除重复项

我设法显示数组的项目,并使用我的 Add in the Front 按钮一一添加新项目。但是字符串值不会显示,我只能看到索引号 1.、2.、3. 等。

我尝试将id="firsttree" 放在<input type="text"> html 标记中,但是当我将它加载到网页上时该数组会消失。

JS

var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];


// Iterate array and display
originalArray.forEach(element => {
    // Creates an Element Node with the specified name.
    let listItem = document.createElement("li");

    // creates a Text Node with the specified text.
    let itemDescription = document.createTextNode(element);

    // append: Add Item or Element
    listItem.appendChild(itemDescription);

    /*document.getElementById("firsttree").innerHTML = originalArray;*/

    // Returns the element that has the ID attribute with the specified value and adds a node to the end of the list of children of the specified parent node
    document.getElementById("firsttree").appendChild(listItem);
});

/**
* Add Items to list
*/
function addItem() {
    // Unshift: Add item to beginning of list
    originalArray.unshift(document.getElementById('firsttree').value);

    // Making the text box empty and re-display
    document.getElementById('firsttree').value = " ";
    disp(); // displaying the array elements
}

/**
* Render array
*/
function disp() {

    var str=" ";
    str = originalArray.length +  '<br> '; // break the lines to form list.

    // Increment the list by 1, i++ if i is less than length
    for (i=1; i < originalArray.length;  i++) // Initial parameter is 1.
    {
        // Adding each element with key number to display string
        str += i + ". "+ originalArray[i]  + "<br> ";
    }

    // Display the elements of the array
    document.getElementById('firsttree').innerHTML=str; 
}

HMTL

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="activity3.css">
        <!-- ol: Ordered numbered list-->

        <!--<script>
            /*var trees = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];*/AbortSignal
            /*document.getElementById("oringinalTree").innerHTML = trees;*/
        </script>-->
    </head>
    <body>
        <h1>Array Methods</h1>
        <br>
        <label>
            Enter new array element here
        </label>
        <input type="text">
        <button type="button" value="Add" onclick="addItem()" >
            Add in the Front
        </button>
        <button type="text">
            Add at the End
        </button>
        <button type="text">
            Add in the Middle
        </button>
        <button type="text">
            Sort
        </button>
        <button type="text">
            Remove Duplicates
        </button>
        <br>
        </form> 

        <h2>List of Trees</h2>
        <h3>Tree Display:</h3>   
        <!-- Must create div to place list under Header-->
        <div class="originalArray">
            <ol id="firsttree"></ol>
            <!--<link rel="stylesheet" type="text/css" href="path/to/your.css" />-->
            <script src="gla3.js"></script>
        </div>
        <h4>Sorted Tree Display:</h4>
    </body>
</html>

css

h3 {
    position: absolute;
    left: 70px;
    top: 200px;
}

h4 {
    position: absolute;
    left: 300px;
    top: 200px;
}

.originalArray {
    position: absolute;
    top: 250px;
    left: 50px;
}

我需要将input 中的字符串添加到数组中然后显示,但我开始时将undefined 添加到数组中,其余的都是空白的。另外,我也不希望看到增量数 (12)。

【问题讨论】:

  • &lt;script src="gla3.js"&gt; 文件中有什么内容?
  • 我的 Javascript 文件

标签: javascript html arrays


【解决方案1】:

1:给你的输入元素添加一个id:

<input type="text" id="new_element">

2:在此行中将firsttree 替换为new_element:

originalArray.unshift(document.getElementById('new_element').value); //  adding element to array

3:在此行中使用 i=0 开始循环:

for (let i=0; i < originalArray.length;  i++)

4:如果您不希望显示数组中的项目数(屏幕截图中的 12),请删除此行:

str = originalArray.length +  '<br> ';

如今,学习一门新的编程语言最重要的事情之一当然是完全理解从堆栈溢出中得到的任何代码,所以如果你想让我解释这些步骤中的任何一个,请不要犹豫。

这是一个添加了其他功能的示例:

var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch',  'aspen'];

    // why not simply use your disp() function
    // to display the array at first ? 
    disp(); 


    // functions to add items

        function addItemFront() {
            originalArray.unshift(document.getElementById('new_element').value); 
            document.getElementById('firsttree').value = " "; 
            disp(); // displaying the array elements
        }
        function addItemEnd() {
            originalArray.push(document.getElementById('new_element').value); 
            document.getElementById('firsttree').value = " "; 
            disp(); 
        }
        function addItemMiddle() {
            originalArray.splice(Math.round(originalArray.length/2), 0, document.getElementById('new_element').value);
            document.getElementById('firsttree').value = " "; 
            disp(); 
        }

    // function to remove duplicate
        function removeDuplicate() {
            originalArray = array_unique(originalArray);
            document.getElementById('firsttree').value = " "; // Making the text box  blank
            disp(); // displaying the array elements
        }

        // more info on this one at: https://stackoverflow.com/questions/25530168/is-there-a-function-like-array-unique-in-jquery
        function array_unique(array){
            return array.filter(function(el, index, arr) {
                return index == arr.indexOf(el);
            });
        }

    // function to display the array
    function disp() {
        var str=" "; 
        for (i=0; i < originalArray.length;  i++){ 
            str += i + ". "+ originalArray[i]  + "<br> ";  
        } 
        document.getElementById('firsttree').innerHTML=str; 
    }

    // function to display the sorted array
    function dispSorted() {
        var str=" "; 
        var sortedArray = originalArray.sort();
        for (i=0; i < sortedArray.length;  i++){ 
            str += i + ". "+ sortedArray[i]  + "<br> ";  
        } 
        document.getElementById('sortedtree').innerHTML=str; 
    }
            .originalArray {
                position: absolute;
                top: 250px;
                left: 50px;
            }
            .sortedArray {
                position: absolute;
                top: 250px;
                left: 450px;
            }
        <h1>Array Methods</h1>
        <br>
        <div class="field">Enter new array element here</div> 
        <input type="text" id="new_element"> 
        <button type="button" onclick="addItemFront();">Add in the Front</button>
        <button type="button" onclick="addItemEnd();">Add at the End</button> 
        <button type="button" onclick="addItemMiddle();">Add in the Middle</button> 
        <button type="button" onclick="dispSorted();">Sort</button> 
        <button type="button" onclick="removeDuplicate();">Remove Duplicates</button>
        <br>
        <h2>List of Trees</h2>

        <div class="originalArray">
            <h3>Tree Display:</h3>   
            <ol id="firsttree"></ol>
        </div>

        <div class="sortedArray">
            <h4>Sorted Tree Display:</h4>
            <ol id="sortedtree"></ol>
        </div>

【讨论】:

  • 好的,谢谢,真的很有帮助!我是 Javascript 新手,我们一次就学到了很多,这些步骤确实很有意义。
  • 您能否帮我解决“中间添加”、“排序”和“删除重复项”(从排序树显示中删除)?我已经尝试过对所有人使用多种方法,但没有一个有效....
  • 好吧,它看起来很棒!谢谢你的帮助!你确实为我节省了很多时间。
【解决方案2】:

对于addItem(),就像提到的@françois-huppé 一样,您需要在输入文本中添加一个id。

function addItem() {
    originalArray.unshift(document.getElementById('new_element').value); 
    document.getElementById('new_element').value = ""; 
    disp(); 
 }

 function disp() {
   let str = "";
   for (let i = 0; i < originalArray.length; i++) { 
      str += `<li>${originalArray[i]}</li>`;
    }

  document.getElementById('firsttree').innerHTML = str;
}

关于disp()函数,有两点需要注意。

  1. 由于您将每个值附加到有序列表&lt;ol&gt;,因此您不需要换行符&lt;br&gt;,因为&lt;li&gt; 默认具有显示块属性,它将在换行。

  2. 您也不需要为项目编号str += i + ". "+ originalArray[i],有序列表会对其进行编号。

你可以在这里查看工作解决方案https://codepen.io/sirwhite/pen/mddKxqr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2023-01-02
    相关资源
    最近更新 更多