我有以下Jquery脚本:
$(document).ready(function() {
// When the submit button of the new team form is clicked...
$('#new_team').submit(function() {
// Disable & rename the save button
$('input#save_button', this).attr('disabled', 'disabled').val('Saving...');
// Fade in the saving message
$("#saving-msg").fadeIn(200);
});
// Perform the AJAX request to the server
$('#new_team').ajaxForm({
url: "/teams/create.json",
type: "POST",
dataType: "json",
beforeSubmit: function(formData, jqForm, options) {},
success: function(response) {
if(response.success == true) {
// If no errors then redirect
window.location = "/teams/" + response.team_id;
} else {
// Enable and rename the save button
$('input#save_button').removeAttr('disabled').val('Save');
// Output errors
$("#error_messages").html(errorMessages(response)).hide().fadeIn(300);
// Fade out save message
$("#saving-msg").fadeOut(200);
// Scroll to the top
window.scrollTo(0,0);
}
}
}); });
是否有简化此脚本并使其可以重复使用不同的表单?
谢谢!
答案 0 :(得分:0)
您两次引用表单的ID;您可以将传递给$(document).ready
的函数抽象为一个函数,该函数接受一个参数(表单的id),然后每次使用闭包只传入一个不同的名称。
function abstracted_ajax_form($formid)
{
...
}
$(document).ready(function() { abstracted_ajax_form('#new_team'); });
答案 1 :(得分:0)
只有几个人。您可以为表单创建一个类,并使用保存按钮的id,而不是使用ID,msg看起来像这样:
<id_of_form>_save_button
<id_of_form>_error_msgs
<id_of_form>_saving_msg
$(document).ready(function() {
$('.ajax_form').submit(function() {
$('.save_button', this).attr('disabled', 'disabled').val('Saving...');
$(this.attr('id')+"_saving_msg").fadeIn(200);
}
);
您可以对AJAX请求使用相同的想法。