2012-02-03 66 views
0

我有一些形式,我想添加類的元素。這裏有一個例子:如何添加樣式到表單?

<form ... id="test1"> </form> 
<form ... id="test2"> </form> 

我發現下面的,但我不明白的前幾行的語法

(function ($) { 

    $.widget("ui.format", { 

     _init: function() { 

      var self = this; //the plugin object 
      var o = self.options; //user options 

      //get all form elements 
      var form = self.element; //the form that reformed was called on 
      var fieldsets = form.find('fieldset'); 
      var legends = form.find('legend'); 
      var text_inputs = form.find('input[type="text"] , input[type="password"] , textarea'); 
      var checkboxes = form.find('input[type="checkbox"]'); 
      var radios = form.find('input[type="radio"]'); 
      var buttons = form.find('input[type="reset"] , input[type="submit"], button'); 

      //add appropraite styles to form elements 
      form.addClass('ui-widget'); 
      fieldsets.addClass('ui-widget ui-widget-content ui-corner-all'); 
      legends.addClass('ui-widget ui-widget-header ui-corner-all'); 
      text_inputs.addClass('ui-widget ui-widget-content ui-corner-all'); 




}); //end plugin 

})(jQuery); 

我特別不明白這一點:

(function ($) { 
    $.widget("ui.format", { 
     _init: function() { 

和最後一行:

})(jQuery); 

有人可以向我解釋它是什麼意思,並通過這三行來引導我。

例如:

  • 什麼是_init意味着
  • 我可以使用「ui.format」混合的情況下,這是函數的名稱?
  • 什麼是.widget的意思,我怎麼能將這個代碼應用到我的表單?我假設我需要從文檔內部以某種方式調用它,然後將其附加到特定的表單ID。
  • 此外,如果我將此應用於我的表單,然後再應用它,會發生什麼情況。它會兩次添加相同的類嗎?

回答

1

(function ($) {開始使用jQuery插件(以及其他JavaScript函數)常用的模式。整個模式是:

(function ($) { //declare an anonymous function that accepts a parameter called '$' 
    //your code goes here 
}(jQuery)); //Close the anonymous function and pass it the jQuery object 

結束語整個事情括號使得它只要它加載執行(即之前的DOM就緒)。

$.widget("ui.format", {開始延長jQuery widget factory傳遞「ui.format」爲「namespace.widgetname」,然後{啓動對象通過

「什麼是_init意味着」:_init: function() {是一個名爲「_init」的函數正在傳入widget工廠的對象中定義。

「我可以對」ui.format「使用混合大小寫:」不,因爲它是正在修改的名稱空間小部件,JavaScript區分大小寫。

至於應用到你的代碼,我以前沒有看到這個插件,所以我不得不引用你在網站上的文檔,你得到它。

通常,通過將選擇器傳遞給jQuery對象並調用該小部件(即$('form#test1').ui.widget();)來應用jQuery小部件。

您還可以使用.addClass()函數添加類。

$(document).ready(function() { 
    $('form#test1').addClass('yourClassHere'); 
    $('form#test1').addClass('yourNextClassHere'); 
    //or just chain them together like so... 
    $('form#test1').addClass('classOne').addClass('classTwo').addClass('classThree'); 
}); 
0

據推測,該腳本的樣子:

(function($) { 
    $.widget("ui.format", { 
    _init: function() { 
     ... 
     ... 
    }); 
})(jQuery); 

第一行(加上最後的)只是意味着在通過腳本解析它實際上將運行它的時候了。即:它會在加載後立即運行。

第二行是隻是調用在兩個參數jquery插件插件和傳球:

一個是字符串「ui.format」 2是一個javascript對象,其中_init被定義爲的函數。

很可能,在插件代碼的某處,_init將被稱爲_init()。

+0

謝謝 - 那麼我將如何重視這一種形式? – Jessica 2012-02-03 02:29:19