2011-07-28 69 views
0

我將如何調用方法showAlert()我試圖存儲一個引用插件與此和$(this)內的自變量,但似乎沒有工作。我在button click事件中調用showAlert。範圍問題裏面的jQuery插件

(function($){ 

     //Add your default settings values here 
     var settings = { 
     //Replace with your own settings 
     testValue:"FOO" 
     } 

     var selectedArr=[]; 
     var self=this; 

     var methods = { 
     init : function(options){ 
      return this.each(function(){ 
      //if options exists, let's merge them with our default settings 
      if(options){ 
       $.extend(settings,options); 
      } 

      var $this=$(this); 
      var button = $this.find('.schedule .time a'); 

      button.click(function(evt){ 
       evt.preventDefault(); 
       selectedArr.push($(this).addClass('selected')); 
       $(this).parent().find('input').attr('checked','checked'); 
       self.showAlert(); 
      }) 
      }); 
     } 
     } 

     showAlert: function(){ 
      alert("Please select an alternitive"); 
     } 

     //Setting namespace. Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object. 
     //See http://docs.jquery.com/Plugins/Authoring for an explaination of the method used here 
     $.fn.chooseAppointment = function(method){ 

     if(methods[method]){ 
      return methods[method].apply(this,Array.prototype.slice.call(arguments,1)); 
     }else if(typeof method === 'object' || !method){ 
      return methods.init.apply(this,arguments); 
     }else{ 
      $.error('Method ' + method + ' does not exist on jQuery.chooseAppointment'); 
     } 
     }; 

    })(jQuery); 

回答

0

你寫的方式,showAlert不是thisself的成員。像這樣methods變量之前剛剛宣佈showAlert

var showAlert = function() { alert("Please select an alternitive"); }; 
var methods = { /* etc etc */ }; 
+0

好吧,但我怎麼會從按鈕事件 – Chapsterj

+0

叫它啊有你不需要使用它。 – Chapsterj

+0

爲什麼你需要在它之前使用var?如果我像在我的例子中那樣忽略var,這意味着什麼。那麼在沒有var的情況下,它的範圍是什麼 – Chapsterj

0

看起來像你只需要做到這一點:

$('#myId').chooseAppointment('showAlert'); 

它看起來像插件調用基於該方法參數的方法,然後將基於傳遞的附加參數等參數。 IE

$('#myId').chooseAppoinment('showAlert', 'Foo'); 

看起來好像是打電話給showAlert('Foo');

+0

你的意思'$ this.chooseAppointment( 'showAlert');'? –

+0

我在任何頁面調用插件的上下文中編寫代碼。 – Tejs