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

标签 javascript html forms interactive

我尝试使用 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;

关于javascript - 使用 document.getElementByID 访问动态生成的 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48784757/

相关文章:

Javascript - 重用变量来创建 DOM 元素

javascript - 谷歌浏览器。从命令行启动离线模式

html - map 覆盖了切换按钮

javascript - JS 将 TARGET 添加到表单

javascript - 无法从 dc.js 数据表中删除空箱

javascript - 如何将页面上的所有文本放入一个字符串中

javascript - (jQuery) 在 cookie 中单击时保存复选框状态

html - 使用 flex 元素作为 flex 容器

asp.net-mvc - ASP.Net MVC 可重用形式作为 RenderAction 或 RenderPartial

javascript - 如果选择了特定的 <option> 值,则导航到 URL