Jquery Extend Existing Function

纵饮孤独 提交于 2019-12-11 05:19:30

问题


I am looking for a way to expand an existing Jquery function to give it more options/parameters.

The one I want to use is $.ajax but this could apply to any jquery function.

I want to be able to call a function like this:

$.adv_ajax()

Which would be an extended version of the $.ajax function like as follows:

 $.adv_ajax({
  custom_parameter: "abc", //my custom one
  url: "test.html",
  context: document.body,
  success: function(){
    $(this).addClass("done");
  }
});

回答1:


Well then just attach your function to the jQuery object:

$.adv_ajax = function(options) {
    // Do stuff like change some options and then call the original
    return $.ajax(options);
}



回答2:


Something like this:


(function($)
{
    // maintain a to the existing function
    var oldAjax = $.ajax;
    // ...before overwriting the jQuery extension point
    $.fn.ajax = function()
    {
        // original behavior - use function.apply to preserve context
        var ret = oldAjax.apply(this, arguments);


        // preserve return value (probably the jQuery object...)
        return ret;
    };
})(jQuery);




来源:https://stackoverflow.com/questions/8798878/jquery-extend-existing-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!