如何在JavaScript中使用表单编写for循环

时间:2017-05-17 15:16:59

标签: javascript php html for-loop

我是JS的新手。

我想在JS中编写一个for循环,它给出了一个选定数量的表单。 这是我到目前为止所得到的。 (也许我必须写一个函数。但我不知道如何继续。)

<!DOCTYPE html>
<html lang="de">
  <head>
    <title>Survey</title>
    <link rel="stylesheet" type="text/css" href="survey.css">
  </head>
  <body>


<h1><?php echo "Title: ".$_POST["title"];
?></h1>


<script>

    var Ausgabe = "";
      for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
            Ausgabe = i + ". question: " + <form>
    <input type="text" id="title" name="title"> 
    </form>
    document.write(Ausgabe)
    }

</script>

  </body>
</html>

欢迎任何提示。

2 个答案:

答案 0 :(得分:0)

您可以使用JavaScript执行此操作:

var Ausgabe = "";
  for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
        Ausgabe = i + ". question: " + "<form><input type=\"text\" id=\"title\" name=\"title\"></form>"
document.write(Ausgabe)
}

在“html”字符串周围添加引号并转义其中的引号(例如type = \“text \”)。

无论如何,我认为最好通过PHP直接进行循环,例如:

<?php
for ($i = 1; $i <= anzahl; $i++) {
    echo "<form><input type=\"text\" id=\"title\" name=\"title\"></form>";
}

我希望它有所帮助,再见。

答案 1 :(得分:0)

我不知道你的目标是什么,但我认为你正在尝试做这样的事情:

&#13;
&#13;
var input = prompt('Enter a number (<= 10):'),
    html = '';

if (Number(input) <= 10) {
  for (var i = 0; i < Number(input); i++) {
    html += '<form>';
    html += '  <input type="text" placeholder="' + i + '">';
    html += '</form>';
  }
} else {
  console.log('The number is too high!');
}

document.body.innerHTML = html;
&#13;
&#13;
&#13;