使用自定义事件和trigger()
!
首先,在表单上放置一个单选按钮,以允许用户在 AJAX/导出到文件之间切换。假设这个字段的名称是submitAction
其次,您的提交侦听器仅根据submitAction
收音机的值来决定接下来会发生什么。这是您触发自定义事件的地方(我们在步骤 3 中定义它们):
$('form.specialform').on('submit',function(e){
e.preventDefault();
var checked = $(this).closest('[name="submitAction"]').filter(':checked');
if(checked.val() == 'ajax'){ //ajax!
$(this).trigger('submitAJAX');
} else { //export to file!
$(this).trigger('submitExport');
}
});
第三,使用两个事件侦听器定义您的自定义事件:
$('form.specialform').on('submitAJAX',function(e){
//do AJAX call here
});
$('form.specialform').on('submitExport',function(e){
//do file export here
});
如您所见,这样做可以避免多次取消绑定和重新绑定相同的事件处理程序的混乱。
这有帮助吗?