如何实现基于用户输入编辑JavaScript数组并实时更新展示?
Fixing Your Editable Number Grid
Let's work through fixing your editable grid implementation — I can spot a few key issues in your code that are causing the problems you're seeing:
Key Issues in Your Current Code
- Invalid HTML syntax: The line
<input id="someInput" type="text" value=<p id="output"></p>>is broken. You can't nest HTML elements inside thevalueattribute of an input; this is why you can't assign array values to that input properly. Additionally, this extra input is redundant since you're already creating individual inputs for each array element in the container. - Duplicating inputs instead of updating them: Your
doStufffunction creates entirely new input elements every time you click submit and appends them to the container, leading to a growing list of inputs instead of updating the existing ones. - Incorrect position targeting: You're trying to get the index from
nameElement.id, but the extra input's ID is fixed assomeInput, so it can never match an array index.
Corrected Implementation
Here's a revised version of your code that meets your requirement: a grid where you can edit any number, click submit, and have the array update and reflect those changes:
<style> #container{ display: grid; grid-template-columns: repeat(9, 8%); gap: 8px; margin-left: 35%; margin-right:25%; margin-top:10%; } #container input { padding: 8px; text-align: center; } body { background-color: grey; } </style> <body> <div id='container'></div> <button id="submitBtn">Submit Changes</button> </body> <script> let grid = [0,1,4,6,3,0,9,3,2]; const container = document.getElementById('container'); const submitBtn = document.getElementById('submitBtn'); // Function to render the grid from the array function renderGrid() { // Clear existing inputs first container.innerHTML = ''; for(let i = 0; i < grid.length; i++){ const input = document.createElement('input'); input.type = 'number'; // Use number input to restrict to numeric values input.id = `grid-${i}`; input.value = grid[i]; container.appendChild(input); } } // Function to update the array from the input values function updateGrid() { // Loop through each input in the container for(let i = 0; i < grid.length; i++){ const input = document.getElementById(`grid-${i}`); // Convert input value to number (default to 0 if empty) grid[i] = input.value ? Number(input.value) : 0; } // Re-render to ensure consistency (optional but helpful for validation) renderGrid(); // Optional: Log the updated array to confirm console.log('Updated grid:', grid); } // Initialize the grid on page load window.onload = renderGrid; // Attach click event to submit button submitBtn.addEventListener('click', updateGrid); </script>
What Changed & Why
- Removed redundant input: We got rid of the broken extra input element since we're using individual inputs for each array index.
- Added
renderGridfunction: This reusable function clears the container and renders fresh inputs based on the currentgridarray. This prevents duplicate inputs and ensures the UI always matches the array state. - Updated
updateGridfunction: Instead of creating new inputs, this function reads the value from each existing input, converts it to a number (to keep the array numeric), updates thegridarray, then re-renders the grid. - Used
numberinput type: This restricts users to entering only numeric values, which helps keep your array consistent. - Cleaner event handling: We use
addEventListenerinstead of inlineonClickfor better practice and separation of concerns.
Now when you edit any number in the grid and click "Submit Changes", the underlying grid array will update, and the UI will refresh to match the new array state.
内容的提问来源于stack exchange,提问作者HrithikLanghi
相关产品推荐
相关产品推荐

