创建一个jQuery回调函数

时间:2013-11-12 20:08:06

标签: javascript jquery

我在理解如何创建回调函数时遇到问题,我可以使用它来扩展选项,如guide中所述。这是我想用于回调的代码摘录;

var chart       =   {};
chart.data      =   $('.liselected').attr("data"); 
chart.command   =   $('.liselected').attr("cmd");
chart.option    =   "option"; // Category of event request
chart.sessionid =   docCookies.getItem("sessionid");
chart.ageType   =   selectedAgeType;
chart.showData  =   showUnderlyingData;

var action  =   function(result, status) {

    $('#thumbnails .error').remove();
    var chart_list  =   "";

    $.each(result, function(i, val){
        chart_list += //Custom HTML Output
    });

    $('#chart_view').html(chart_list);
};

$.post("jsoncommand", JSON.stringify(chart), action);

因此我可以使用$("a").on("click", postcommand(eventrequest))进行调用,我尝试创建这样的函数;

$.fn.postcommand = function(){
    var settings = $.extend({
        item        :   {},
        data        :   $('.liselected').attr("data"),
        command     :   $('.liselected').attr("cmd"),
        option      :   "specify query",
        sessionid  :    docCookies.getItem("sessionid"),
        ageType     :   selectedAgeType,
        showData    :   showUnderlyingData,
    }, options );

    return //How do I make the output of HTML result is customizable?
};

但当然,我的尝试是失败的。勺子喂养很好,但你总能给我一个提示,我会尝试自己探索。谢谢!

1 个答案:

答案 0 :(得分:1)

查看jQuery插件部分可能是个好主意:http://learn.jquery.com/plugins/advanced-plugin-concepts/。你可以这样做:

$.fn.postcommand = function (options) {

    // define some default values for your plugin
    var default = {
        callback: function () {}
    }

    // merge default settings,  with the ones given  
    var settings = $.extend( {}, defaults, options );

    return this.each(function() {
        var $this = $(this);
        $this.on('click', function(event) {
          settings.callback();
          event.preventDefault();
        });
    }
});

然后在某些链接上使用您的插件:

$('a.useCallback').postcommand();