【问题标题】:How to write a for loop with forms in JavaScript如何在 JavaScript 中编写带有表单的 for 循环
【发布时间】:2017-05-17 15:16:58
【问题描述】:

我是 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>

欢迎任何提示。

【问题讨论】:

  • 您似乎忘记将字符串放在引号中,导致语法错误。您还可以通过重复使用相同的id 来生成无效的 HTML。
  • 你想给 JavaScript 表单值吗?

标签: javascript php html for-loop


【解决方案1】:

你可以用 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>";
}

希望对你有帮助,再见。

【讨论】:

  • 哦,当然,在文本和表单上都会更好,反正在他的代码中没有 id。
  • 您正在编写带有 ID 属性输入的表单
  • 非常感谢,这行得通。 @happymacarts:这是个好主意,但不适用于我的代码。它说意外的令牌。有人可以帮忙吗?
【解决方案2】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多