1

在编写插件时,您如何传递基于事件的可选函数。我可以通过在调用过程中手动将函数名称作为字符串编写,然后将其作为字符串中的 onclick="" 添加到 this.html() 中,但那是 naff。我想成熟地将该函数作为可选参数传递,并可选择将其添加为点击条件事件

文件

<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 );
4

1 回答 1

1

试试这些:

$("#addon"+(parseInt(i))).click(heading.click_callback); 
$("#addon"+(parseInt(i))).click(function(){heading.click_callback();}); 
于 2013-02-18T12:58:26.227 回答