到目前为止,所有其他答案的问题似乎是,当提交按钮被禁用时,它会导致与其关联的name-value 数据对不会被发布,因为按钮被禁用在发布数据之前。但是,submit 按钮通常不用于传递数据,因此解决此问题的一种方法是简单地将数据与单独的隐藏 input 元素相关联。
HTML:
<form id="form" target="_blank" method="post" action="page2.php">
<input type="hidden" name="btn" value="btn"></input>
<input id="submit-button" type="submit" value="btn">
<br />
</form>
请注意,我在表单中添加了ids 并提交按钮以供在 JavaScript 中选择。
JavaScript:
// Get the form and the submit button.
var form = document.getElementById('form');
var submitButton = document.getElementById('submit-button');
// Disables the submit button.
function disableSubmitButton() {
submitButton.setAttribute('disabled', '')
}
// Disable the submit button when the form is submitted, with fallback for IE 5-8.
if (form.addEventListener) {
form.addEventListener('submit', disableSubmitButton, false);
} else {
form.attachEvent('onsubmit', disableSubmitButton);
}
如果您有两个不同的提交按钮,您还可以通过设置隐藏的 input 元素的值来根据按下的按钮向操作页面传递不同的值:
HTML:
<form id="form" target="_blank" method="post" action="page2.php">
<input id="hidden-input" type="hidden" name="button-pressed" value=""></input>
<input id="submit-button-1" type="submit" value="Submit Button 1">
<input id="submit-button-2" type="submit" value="Submit Button 2">
<br />
</form>
JavaScript:
// Get the form and the hidden input.
var form = document.getElementById('form');
var hiddenInput = document.getElementById('hidden-input');
// Set the value of the hidden input depending on which button was pressed.
function setHiddenInputValue(event) {
// Get the id of the button that was pressed.
pressedButtonId = event.target.id;
// Set the value of the hidden input element to be the same as the id of the pressed button.
hiddenInput.setAttribute('value', pressedButtonId);
// Disables the submit button that was pressed.
function disableSubmitButton(event) {
event.target.setAttribute('disabled', '')
}
// Disable the submit button when the form is submitted, with fallback for IE 5-8.
if (form.addEventListener) {
form.addEventListener('submit', function(event) {
// Event object fallback for IE 5-8.
if (!event) {
event = window.event;
}
setHiddenInputValue(event);
disableSubmitButton(event);
}, false);
} else {
form.attachEvent('onsubmit', function(event) {
// Event object fallback for IE 5-8.
if (!event) {
event = window.event;
}
setHiddenInputValue(event);
disableSubmitButton(event);
});
}