You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码无法运行:如何实现动态生成页面元素?

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 change event — you'll want to use click instead for button interactions.
  • The cols and rows attributes for <textarea> are numeric values, not pixel measurements (drop the px suffix 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:25:21