代码无法运行:如何实现动态生成页面元素?
Fixing Your Dynamic Element Generation Code
Hey there! Let's get your code working properly. I noticed a few key issues in your snippet that are keeping it from running, plus some tweaks to make it more robust.
Key Problems in Your Original Code
- Buttons don't trigger a
changeevent — you'll want to useclickinstead for button interactions. - The
colsandrowsattributes for<textarea>are numeric values, not pixel measurements (drop thepxsuffix entirely). - Your code cuts off mid-attribute setup at
textarea.setAtt...— looks like you were halfway through setting a property. - Using a fixed
id="tid"will create duplicate IDs if you click the button multiple times (HTML requires unique IDs per element on a page).
Corrected & Complete Code
Here's a polished, working version with comments explaining each step:
<html> <head> <script type="text/javascript"> function formQuestion(button_id, question_no) { // First, grab the button and add a safety check to avoid errors const button = document.getElementById(button_id); if (!button) { console.error(`Button with ID ${button_id} wasn't found!`); return; } // Use click event (correct for buttons) instead of change button.addEventListener('click', function() { // Create a container div to group elements neatly const div = document.createElement("div"); div.style.marginBottom = '1.5rem'; // Add spacing between generated sections document.body.appendChild(div); // Create the textarea element const textarea = document.createElement("textarea"); // Fix cols/rows (no px suffix — these are numeric properties) textarea.setAttribute("cols", "90"); textarea.setAttribute("rows", "20"); textarea.setAttribute("style", "border:solid 4px black; resize:none"); // Use a unique ID tied to question_no to avoid duplicates textarea.setAttribute("id", `tid-${question_no}`); // Optional: Add a placeholder to guide users textarea.placeholder = `Enter content for Question ${question_no}`; // Append textarea to the container div (cleaner DOM structure) div.appendChild(textarea); }); } // Initialize the function after the page fully loads (so elements exist) window.onload = function() { // Example: Attach the function to a button with ID "addQuestionBtn" formQuestion("addQuestionBtn", 1); }; </script> </head> <body> <!-- Example button to trigger element generation --> <button id="addQuestionBtn">Add Question 1</button> </body> </html>
Quick Extra Tips
- Wrapping the textarea in a div makes it easier to style and organize generated content later.
- The safety check for the button prevents console errors if you mistype the button ID.
- Using a unique ID (
tid-${question_no}) ensures you can target individual textareas later if needed (e.g., to read their values).
内容的提问来源于stack exchange,提问作者core
相关产品推荐
相关产品推荐

