【问题标题】:Accessing dynamically generated DIV using document.getElementByID使用 document.getElementByID 访问动态生成的 DIV
【发布时间】:2018-02-14 10:21:55
【问题描述】:

我正在尝试使用 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";
  }
}

【问题讨论】:

    标签: javascript html forms interactive


    【解决方案1】:

    document.getElementById 通过其 ID从文档获取一个元素。

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


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

    newDiv.innerHTML = html2;
    

    【讨论】:

    • 是的,问题已解决,但没有弹出新问题。你也可以看看吗>
    • "您还没有将 div 添加到文档中"
    • 怎么做?我不明白。
    • 你设法弄清楚createElementMDN documentation for createElement 有例子。
    • 我设法让它工作,但代码以一种不寻常的方式工作。我现在正在使用 document.body.insertBefore。再次编辑代码供您查看。请查看编辑历史记录。
    猜你喜欢
    • 2017-04-12
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2013-06-28
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多