JS动态添加表单按钮

Form button add dynamically in JS

我试图在 JavaScript 中动态添加一个表单,但是当我点击提交按钮时没有任何反应。我知道那是因为按钮没有监听器,但我不知道我必须在监听器中添加什么才能正常发送按钮行为。

这是我的一些代码

document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("partTwo").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("partTwo").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>T&eacute;l&eacute;charger le rapport</button>";
document.getElementById("partTwo").innerHTML += "</form>";

我希望听众将表格发送到我的 client.process.php

我知道这是一个初学者问题,但我们将不胜感激。 谢谢

Working fiddle.

您应该在 form 内添加输入,而不是在 div partTwo 内,因此您的代码应该像:

document.getElementById("partTwo").innerHTML += "<form id='download_report' method='post' class='form-horizontal' role='form' action='include/client.process.php'>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='jobid' value='" + jobId + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='job' value='" + job_details.heavyInfosJson + "'/>";
document.getElementById("download_report").innerHTML += "<input type='hidden' name='download_report' value='1'/>";
document.getElementById("download_report").innerHTML += "<button id='download_report_button' type='submit' class='btn btn-default btn-xs'>T&eacute;l&eacute;charger le rapport</button>";

希望对您有所帮助。

问题是 <form> 标签自动关闭。 innerHTML returns 格式正确 html。参见 this question

您应该考虑使用 createElement 而不是 innerHTML,请参阅 2946656

以下是如何创建表单并将其附加到页面的基本示例:

var form = document.createElement("form");
form.setAttribute('action', 'contact.php');
form.setAttribute('method', 'POST');

var inputField = document.createElement("input");
inputField.setAttribute('value', 'example');
form.appendChild(inputField);

document.body.appendChild(form);