Override .load function of jQuery

…衆ロ難τιáo~ 提交于 2020-01-05 07:58:08

问题


I have site which uses $(selector).load(path) function in more than 300 pages. Now my client's requirement has changed and I need to access cross domain to call these pages.

For the purpose I have to replace all the .load( function to some cross-domain function with the help of YQL.

Is it possible to override my .load function and call prevent default and do my own code?


回答1:


There is no clean way to do this, especially since $.fn.load does different things depending on the arguments and replacing it would affect all those subfunctions.

However, jQuery supports AJAX hooks which you might be able to achieve what you want.

In case all you need is support for IE's XDomainRequest, have a look at this plugin: https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js


Anyway, if you really want to replace the ajax load function of jQuery, this code should do it:

var _load = $.fn.load;
$.fn.load = function(url, params, callback) {
    if(typeof url !== "string") {
        return _load.apply(this, arguments);
    }

    // do your ajax stuff here
}

This is exactly the same check jQuery uses to decide whether someone wants to bind the onload event or perform an AJAX load.




回答2:


The most reasonnable way seems to me to not overload the jquery function but simply do a search and replace in your favorite editor to replace $(xxx).load( by yourpackage.load(xxx,.

This can be done in minutes even on 300 js files. Future changes will be easier and the code will be more readable as the reader never expects a jquery function to do something that isn't on the doc.




回答3:


Yes, it's possible:

$.fn.load = yourFunc;

Is it recommended? I think not.



来源:https://stackoverflow.com/questions/11153827/override-load-function-of-jquery

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