对于我的小项目,我想拥有TextAreas,并且应该在for循环中生成textAreas。



的HTML

<h2>Settings for new Code:</h2>

<p>Amount of Checks:</p>
<input id="NumOfButtons"
       name="NumOfButtons"
       pattern=""
       size="30"
       spellcheck="false"
       title="amount of Checks"
       value="">

<script>

    let input = document.getElementById("NumOfButtons");
    input.addEventListener("keyup", function (event) {
        let listTA;
        if (event.keyCode === 13) {
            event.preventDefault();
            var x = parseInt(document.getElementById("NumOfButtons").value);
            listTA = new Array(x);
            for (let i = 0; i < x; ++i) {
                var textarea = document.createElement("textarea");
                textarea.name = "TextArea";
                textarea.maxLength = "100";
                listTA[i] = textarea;
                input.appendChild(textarea);
            }
        }
    });
</script>


输出应该是已键入到现有textArea中的TextAreas的数量。

最佳答案

答案很简单:HTML <input>元素不是容器-它不能容纳子元素。
您想要做的是创建一个空的<div>并将textareas附加到它后面。



let input = document.getElementById("NumOfButtons");
input.addEventListener("keyup", function(event) {
  let listTA;
  if (event.keyCode === 13) {
    event.preventDefault();
    var x = parseInt(document.getElementById("NumOfButtons").value);
    listTA = new Array(x);
    for (let i = 0; i < x; ++i) {
      var textarea = document.createElement("textarea");
      textarea.name = "TextArea";
      textarea.maxLength = "100";
      listTA[i] = textarea;
      document.getElementById("theDiv").appendChild(textarea);
    }
  }
});

<h2>Settings for new Code:</h2>

<p>Amount of Checks:</p>
<input id="NumOfButtons" name="NumOfButtons" pattern="" size="30" spellcheck="false" title="amount of Checks" value="">
<div id="theDiv">
</div>

关于javascript - Javascript:生成自定义数量的TextAreas,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57075281/

10-12 06:57