2011-06-30 28 views
0

當我把這個插件裏面的功能與$.fn.

你可以看到,我的意思here什麼是錯我的jQuery插件。我有兩種形式,它們共享相同的插件,

 $(document).ready(function(){ 

     $("#search-title").post_form_public(); 
     $("#subscribe-email").post_form_public(); 

    }); 

第一種形式將第二種形式被觸發時不再工作。

如果我只將插件附加到一個表單上,它可以正常工作。

下面是插件代碼裏面的一些詳細信息,

post_form_public: function(options) { 

    // Set the default values, use comma to separate the settings, example: 
    var defaults = { 
     top:   250, // The top of the proceesing popup and the result popup. 
     width:   400 // The width of the proceesing popup and the result popup. 
    } 

    var options = $.extend(defaults, options); 
    var o = options; 

    var $cm = this.submit(function(e){ 

     var object = $(this); 

     // Get the path from attribute of action in the form. 
     var target_postpath = object.attr('action'); 
     var top = o.top; 
     var width = o.width; 

     // Keep the lines below for checking. 
     alert($cm.selector); 

     // Disable the submit button so that you won't click it twice while the ajax is processing the form. 
     // Must use true or false for jquery > 1.6. 
     $('input[type=submit]',$($cm.selector)).attr('disabled', true).css({opacity:0.4}); 

     // Post the form . 
     $.post(target_postpath,object.serialize(),function(xml){ 

      //process_posted(xml); // two forms work fine with this! 
      $.fn.post_form_public.process_posted(xml); // but not with this! 

     }); 

     return false; 

    }); 

    // Callback function for proccesing the deleted item. 
    //function process_posted(xml) 
    $.fn.post_form_public.process_posted = function(xml) 
    { 

     // Enable the submit button again after processing the xml output. 
     // Must use true or false for jquery > 1.6. 
     $('input[type=submit]',$($cm.selector)).attr('disabled', false).css({opacity:1}); 

    } 

} 

但是,如果我只是做了功能,無需$.fn.,那麼這兩種形式將正常工作。我如何使用$.fn.並使多個表單起作用!?您可以看到代碼here

謝謝。

回答

1

變量

$.fn.post_form_public.process_posted 

...只能存儲一個功能。第二次調用插件時,這將被覆蓋。在有效的表單中,您有一個函數形成$cm變量的值 - 並且您爲每個調用post_form_public創建了一個函數。

這個函數的工作形式是怎麼回事?

一個將其存儲在您的post_form_public對象的方法可能是這樣的:

if(!$.fn.post_form_public.process_posted) $.fn.post_form_public.process_posted = {}; 
$.fn.post_form_public.process_posted[$cm.selector] = function(xml) { 
    //... 
}; 

...和你post回調中調用它:

$.fn.post_form_public.process_posted[$cm.selector](xml); 
+0

非常感謝這個! 「這個函數的形式有什麼用?」 - 對於工作的formn沒有任何問題。我可以問這是什麼意思,並且意味着 - 'if(!$ .fn.post_form_public.process_posted)$ .fn.post_form_public.process_posted = {};'thanks :-) – laukok

+0

@lauthiamkok:該行檢查屬性'process_posted '存在,如果不存在,則將其創建爲新的空對象。這些函數然後被存儲爲該新對象的屬性。 – sje397

+0

明白了!非常感謝你! :-)))) – laukok

0

該代碼小艾weired。重新排序了一些東西,這應該可以做到。

http://jsfiddle.net/trgpa/

不能測試它自己上的jsfiddle上的jsfiddle Ajax的post請求「search_title_xml.php」拋出404