2013-02-18 19 views
1

在編寫插件時,如何傳遞基於事件的可選函數。我可以通過在調用過程中將函數的名稱手動編寫爲字符串,然後將其作爲字符串中的onclick =「」添加到this.html()中,但這是naff。我想成熟傳遞函數作爲可選參數,並選擇將其添加爲點擊條件事件jQuery插件 - 在選項中傳遞函數 - 但作爲事件觸發

文檔

<div id="grid"></div> 
<script>  
$(function() { 
    $("#grid").myaddon({ 
     "headings" : [ 
      { 
       "title" : "hello", 
       "click_callback" : function(){ 
        alert('hi'); 
       } 
      }, 
      { 
       "title" : "there" 
      } 
     ] 
    }); 
}); 
</script> 

和插件本身

(function($) { 

    var methods = { 
     init : function(options) { 

      var defaults = { 
       "title": "text", 
       "click_callback": function() {} 
      } 
      for(var i=0; i<options.headings.length; i++) { 
       var heading = $.extend({},defaults,options.headings[i]); 
       this.html("<div id=\"addon"+(parseInt(i))+"\" >" + heading.title + "</div>"); 
       if (typeof heading.click_callback == 'function') { 
        $("#addon"+(parseInt(i))).click(function() { heading.click_callback.call(this) }); //this doesn't work 
        $("#addon"+(parseInt(i))).click(function() { heading.click_callback.call() });  //this doesn't work 
        $("#addon"+(parseInt(i))).click(heading.click_callback.call());     //this doesn't work 
        $("#addon"+(parseInt(i))).click(eval(heading.click_callback.call()));    //(in desperation) this doesn't work 

        //(edit) 
        $("#addon"+(parseInt(i))).click(heading.click_callback);    //(!!thanks Robert Fricke!) thanks to the answer from Robert Fricke I know this works 
        //(/edit) 
       } 
      }    
     } 
    } 
    $.fn.myaddon = function(method) { 

     // Method calling logic 
     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.myaddon'); 
     } 
    }; 
})(jQuery); 

回答

1

嘗試這些:

$("#addon"+(parseInt(i))).click(heading.click_callback); 
$("#addon"+(parseInt(i))).click(function(){heading.click_callback();}); 
+0

哇! '$(「#addon」+(parseInt(i)))。click(heading.click_callback);'謝謝,做過了......可能太明顯了,不能試試謝謝! – user2083181 2013-02-18 13:10:32