求助:点击按钮动态向数组添加元素失败,文本框内容无法存入数组
Fixing Your Array Addition Issue
Let's walk through the problems in your code and fix them step by step:
1. HTML Syntax Errors
Your input elements are missing the = sign in the id attributes—this breaks JavaScript's ability to select them correctly. Here's the corrected HTML:
<input id="item" type="text"> <input id="clickme" type="submit" value="Add Item"> <!-- Added a visible label for the button -->
2. Key JavaScript Issues & Fixes
Your JS code has a few critical mistakes that are preventing the array from updating:
- Wrong Selector: You’re targeting
#send-btn, but your button’s actual id isclickme. - Invalid Variable Syntax:
var = item $("#item").val()is backwards (should bevar item = $("#item").val()), andvar itemofarrays[]isn’t valid for initializing an array. - Array Scope: If you declare the array inside the click handler, it resets to empty every time you click the button. Declare it outside to keep your items between clicks.
- Missing Array Push: You need to use
array.push(item)to add the input value to the array.
Corrected Full JavaScript Code
// Initialize the array outside the click handler so it retains items between clicks let itemofarrays = []; // Target the correct button id $('#clickme').click(function() { // Get the input value and trim extra whitespace var item = $("#item").val().trim(); // Only add to the array if the input isn't empty if (item) { // Add the item to the end of the array itemofarrays.push(item); // Clear the input field for the next entry $("#item").val(''); // Show the updated array (console.log is better for debugging than alert) console.log("Current array:", itemofarrays); // Optional: Alert the user with a readable list alert("Items in array: " + itemofarrays.join(', ')); } else { alert("Please enter an item first!"); } });
Quick Explanation of Improvements
- Persistent Array: Declaring
itemofarraysoutside the click function ensures it doesn’t reset each time you click. - Input Validation: We skip adding empty strings to avoid cluttering the array.
- Better UX: Clearing the input field after adding an item makes it easier to enter the next one.
- Clear Display:
console.loglets you see the array’s structure in your browser’s dev tools, while the alert shows a user-friendly comma-separated list.
This should resolve your issue—now when you enter text and click the button, the item will be added to the array correctly!
内容的提问来源于stack exchange,提问作者za1782852
相关产品推荐
相关产品推荐

