1

アドオンを書く際に、イベントベースのオプション機能をどのように渡しますか。関数の名前を呼び出し手順で文字列として手動で記述し、それを this.html() に onclick="" として文字列に追加することで実行できますが、それは面倒です。関数をオプションの引数として成熟させて渡し、オプションでクリック条件付きイベントとして追加したいと思います

ドキュメント

<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 に答える