这个JQuery脚本可以简化吗?

问题描述:

我有以下的jQuery脚本:这个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); 
    } 
    } 
}); }); 

反正是有简化这个脚本,并使其可重复使用于不同的形式?

  • 始终只一个表单的页面
  • 的按钮始终标示相同
  • 每个表单上有一个唯一的ID

谢谢!

+0

这是不是真的很好的做法,但由于只有不断一种形式,你可以只使用选择$(“形式”)来引用的形式。然后引用该按钮表示形式的孩子,这样你可以使用$(本).find(“#输入save_button”)。 – user120242 2009-08-13 01:48:02

只是几个thougths。除了使用ID,您可以为表单创建一个类,并有保存按钮的ID和味精是这样的:

<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请求。

+1

我认为这将是更容易使用$(本).find,去寻找形式的范围内的按钮。 – user120242 2009-08-13 01:47:02

+0

不错的通话,jQuery的岩石! – imjoevasquez 2009-08-13 02:01:03

您引用表单的ID两次;你可以代替抽象传递给$(document).ready掳到接收一个参数(形式的ID),然后函数的功能只是每次使用封闭传递一个不同的名称。

function abstracted_ajax_form($formid) 
{ 
    ... 
} 

$(document).ready(function() { abstracted_ajax_form('#new_team'); });