2012-05-04 139 views
2

我正在創建一個簡單的jQuery插件名爲togglebutton。我的問題在底部。 這裏是代碼。需要幫助創建jquery插件

/** CSS */ 
.toggle-button{ 
    -moz-border-radius:4px; 
    border-radius:4px; 
    border:solid gray 1px; 
    padding:4px; 
    color:#fff; 
} 
.state-on{ background:gray; } 

.state-off{ background:blue; } 


/** JQuery Plugin Definition */ 
jQuery.fn.togglebutton = function (options) { 
    myoptions = jQuery.extend ({ 
    state: "off", 
    }, options); 

    this.click(function(){ 
     myoptions.click; 
     opt = options; 
     $this = $(this); 
     if(opt.state == 'on'){ 
      turnoff($this); 
      opt.state = 'off'; 
     } 
     else if(opt.state == 'off'){ 
      turnon($this); 
      opt.state = 'on'; 
     } 
    }); 

    this.each(function() { 
     this.options = myoptions; 
     $this = $(this); 
     opt = this.options; 

     if(opt.state == 'on'){ 
      $this.attr('class', "toggle-button state-on"); 
     } 
     else if(opt.state == 'off'){ 
      $this.attr('class', "toggle-button state-off"); 
     } 

    }); 

    function turnon($this){ 
     $this.attr('class', "toggle-button state-on"); 
    } 
    function turnoff($this){ 
     $this.attr('class', "toggle-button state-off"); 
    } 
} 

/** How to Call */ 
$('#crop').togglebutton({state:'off'}); 

我將添加到我的jQuery插件的定義是什麼,所以我可以調用它是這樣的:

$('#crop').togglebutton({ 
    state:'off', 
    click: function(event, ui) { 
     val = ui.value; 
    } 
}); 

任何幫助深表感謝。我是這個東西的新手。開始

回答

1
$.fn.hello = function(options) { 

    return this.each(function() { 

    }); 
}; 

然後ü可以用上面的插件以下列方式。 。

$('.tip').hello();