代码之家  ›  专栏  ›  技术社区  ›  Matt Hutch

使用输入编号创建具有唯一ID的段落

  •  0
  • Matt Hutch  · 技术社区  · 6 年前

    我有点困在javascript问题上了。我正试图使一个输入数字字段操纵一个段落被创建的次数,我已经开始工作了。我有点纠结的地方是让它给每个段落一个唯一的id并添加到内容文本编号中。

    是否有人知道我如何解决这个问题,因为目前它正在创建具有相同ID和相同内容文本编号的每个段落?

    function updatePage() {
      // Get input value
      var numberInput = document.getElementById("numberInput").value;
    
      // Will be used to store all <p> contents
      var template = "";
    
      while (numberInput > 0) {
        // Add all contents into template
        template += '<p id="p1">Content - 1<p/><br>';
    
        numberInput--;
      }
      // Append upon clicking
      document.getElementById("content").innerHTML = template;
    }
    <input type="number" value="1" id="numberInput">
    <br>
    <input type="button" value="Update" onclick="updatePage()">
    <div id="content">
      <p id="p1">Content - 1<p/><br>
    </div>
    2 回复  |  直到 6 年前
        1
  •  0
  •   winner_joiner    6 年前

    你的意思是这样的:
    ( 只是在 数字输入 身份证件 以及 模板 . )

    function updatePage() {
      // Get input value
      var numberInput = document.getElementById("numberInput").value;
    
      // Will be used to store all <p> contents
      var template = "";
      var idx = 1 
      while (idx <= numberInput ) {
        // Add all contents into template
        template += '<p id="p' +idx + '">Content - ' + idx  + '<p/><br>';
        
        idx++;
      }
      // Append upon clicking
      document.getElementById("content").innerHTML = template;
    }
    <input type="number" value="1" id="numberInput">
    <br />
    <input type="button" value="Update" onclick="updatePage()">
    <div id="content">
      <p id="p1">Content - 1<p/><br />
    </div>
        2
  •  0
  •   brk    6 年前

    像这样连接输入值 '<p id="p_'+numberInput+'">

    function updatePage() {
      // Get input value
      var numberInput = document.getElementById("numberInput").value;
    
      // Will be used to store all <p> contents
      var template = "";
    
      while (numberInput > 0) {
        // Add all contents into template
        template += '<p id="p_' + numberInput + '">Content - 1<p/><br>';
    
        numberInput--;
      }
      // Append upon clicking
      document.getElementById("content").innerHTML = template;
    }
    <input type="number" value="1" id="numberInput">
    <br>
    <input type="button" value="Update" onclick="updatePage()">
    <div id="content">
      <p id="p1">Content - 1
        <p/><br>
    </div>