对于一个使用 GET
方法的表单,我需要将按钮的值包含在查询字符串中,避免在表单提交时丢失它。
我使用了 event.preventDefault()
并在 JS 脚本中添加了按钮的名称和值作为隐藏的 <input>
字段。
JS 脚本:
$( function() {
$(document).on("click", ".delete", function(event) {
event.preventDefault();
$( "#dialog-confirm" ).dialog({
draggable: false,
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Delete items": function() {
$( this ).dialog( "close" );
$('<input />').attr('type', 'hidden')
.attr('name', 'action')
.attr('value', 'delete')
.appendTo('#myform');
$('#myform').submit();
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
表单模板
<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<form id="myform" action="#myurl" method="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input class="delete" type="submit" name="action" value="delete">
</form>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Dialog - Modal confirmation</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$(document).on("click", ".delete", function(event) {
event.preventDefault();
$( "#dialog-confirm" ).dialog({
draggable: false,
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Delete items": function() {
$( this ).dialog( "close" );
$('<input />').attr('type', 'hidden')
.attr('name', 'action')
.attr('value', 'delete')
.appendTo('#myform');
$('#myform').submit();
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
</script>
</head>
<body>
<div style="display:none" id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<form id="myform" action="#myurl" method="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input class="delete" type="submit" name="action" value="delete">
</form>
</body>
</html>
<input type="hidden" name='id' value='要删除的ID' />
,这使得这些表单之间有所不同。 - Omu$(this).closest('form')
,然后只需在删除按钮的处理程序中调用currentForm.submit()
,无需使用ID...并且只需更改删除点击处理程序以使用类或属性选择器。 - Nick Craverreturn false
! - Nick Craver