使用 document.getElementByID 访问动态生成的 DIV

Accessing dynamically generated DIV using document.getElementByID

我正在尝试使用 document.getElementById 访问动态生成的 DIV,但无法将 属性 innerHTML 设置为 null,这很明显。

基本上我正在尝试构建一种交互式表单,就像 https://www.typeform.com/

我想为每个问题创建单独的 DIV。

这是我到目前为止所做的:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Interactive Forms</title>
    <script src="script.js"></script>
  </head>
  <body>
    <center>
      <div id="playArea">
          <h3>Hello Stranger! Let's start</h3> <br/>
          <button id="start" onclick="Questions()">Let's start</button><span>or Hit Enter</span>
      </div>
    </center>
  </body>
</html>

script.js

    var questions = [
    "Hey, what's you name?",
    "Can I know your E-mail ID please?",
    "Would you also like to subscribe to the newsletter?"
];
var html = "";
var i =0;
addEventListener("keydown", function(event){
  if(event.keyCode==13){
    Question();
  }
  if(event.code==39){
    nextQuestion();
  }
});
function Question(){
    html = questions[0]+"<br>"+"<input type='text' class='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
    document.body.innerHTML = html;
    // document.getElementById("playArea").innerHTML = html;
    i++;
}
function nextQuestion(){
  if(i<questions.length){
    var html2 = "";
    newDiv = document.createElement("div");
    check="'answer"+i+"'";
    console.log("'answer"+i+"'");
    newDiv.setAttribute("id", "'answer"+i+"'");
    console.log(newDiv.id);
    html2 = questions[i]+"<br><input type='text' id='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
    newDiv.innerHTML = html2;
    oQ = document.getElementById("otherQuestions");
    document.body.insertBefore(newDiv, oQ);
    i++;
}
  else{
  document.body.innerHTML = "Thank you for the response";
  }
}

document.getElementById 通过其 ID 从文档.

获取一个元素

您还没有将 div 添加到文档中,因此找不到它。


也就是说你已经拥有元素!无需在文档中或其他任何地方搜索它。

newDiv.innerHTML = html2;