簡體   English   中英

如何使用 DOM 將輸入項推送到空數組並使其 output 到 h1 標記?

[英]How to push an input item to an empty array and have it output to h1 tag using the DOM?

我創建了一些輸入文本框,用於將項目添加到數組中。 但是,我能夠讓項目顯示在我聲明顯示結果的 DOM 中,但這些項目沒有被添加到數組中。 我創建了一個空數組來接受 HTML 頁面上輸入文本框中的值。 請幫助我使用推送方法。

<body>
<script>
function groceries() {
let grocery = [];    
const x = document.querySelector(".add").value; 
let count = grocery;
grocery = x;
console.log(count);
console.log(grocery);

document.querySelector(".result").innerHTML = grocery;
 return count;

}

</script>

<h1 class="result">RESULTS</h1>

<div class="center">
<label for="">Date Time</label><br>
<input type="datetime" name="" id=""><br>

<!--Code below is for search-->
<label for="search">Search</label><br>
<input class="search" type="search" name="search" placeholder="Search" id=""><br>

<!--//This line will add items to the grocery list, array.-->
<label for="grocery">Enter groceries</label><br>
<input class="add" type="text" name="" placeholder="Enter Groceries" id=""><br>

<!--This line removes item from the grocery list/ array.-->
<label for="grocery">Remove groceries</label><br>
<input class="remove" type="text" name="" placeholder="Remove Groceries" id=""><br><br>

<!-- Button to run the function above starting at line 13-->
<button type ="button" class="btn btn-lg btn-primary" onclick="groceries()" >Enter grocery</button>

這是因為每次調用 function 時數組都會被重置為空。 將數組存儲在 func 之外將阻止它被重置。 您還需要將項目推送到數組中。

            let grocery = [];    

            function groceries() {
                const x = document.querySelector(".add").value; 
                grocery.push(x)
                document.querySelector(".result").innerHTML = grocery;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM