扫码关注官方订阅号
面试要求自己封装个插件,感觉不会
光阴似箭催人老,日月如移越少年。
自己想去尝试的时候。
到你自己懒得复制粘贴的时候就可以了。复制的复制的,你想给自己节约时间,然后你就发现,我把这些代码放在一个模块里,然后调用就可以了。
最简单的封装一个ajax
jQuery的Hello World插件还是很简单的.
//调用:输出选择器对象el和参数options $("html").foo({key: "value"}); /* jquery.foo.js */ (function($){ $.foo = function(el, options) { console.log(el); console.log(options); }; $.fn.foo = function(options) { $.foo(this, options); }; })(jQuery);
下面是我总结的一个精简的jQuery PJAX插件:
(function($){ $(function(){ //调用插件,用户点击.pjax块里的属性为data-pjax的链接时触发PJAX无刷新加载. $(document).pjax("a[data-pjax]", ".pjax"); }); })(jQuery); /* jquery.pjax.js */ (function($){ $.fn.pjax = function(selector, container) { //IE9/8/7/6不支持HTML5 onpopstate,自然不会执行插件 if("onpopstate" in window) { //AJAX加载函数 var load = function(href) { var time = 600; $(document).trigger("pjax:start", [time]); //执行开发者的自定义事件(如:显示加载进度条) var start = (new Date()).getTime(); $.ajax({ type: "GET", url: href, data: {_pjax_: start} }).done(function(data){ //在回调函数中解析出head中的title和body中的指定块并更新(这样服务器端就不需要改变输出格式) var dom = $("<p>").html(data); var title = dom.find("title").first().text(); var content = dom.find(container).first().html(); document.title = title; $(container).first().html(content); var spend = new Date().getTime() - start; setTimeout(function(){ $(document).trigger("pjax:done"); //执行开发者的自定义事件(如:隐藏加载进度条) }, spend >= time ? 0 : time - spend); }).fail(function(){ window.location.reload(); }); }; history.replaceState({href:location.href}, "", location.href); //用户点击后退和前进按钮时触发该事件 window.onpopstate = function() { if(history.state != null) { //返回前进都是重新加载页面而不是访问浏览器历史记录缓存 load(history.state.href); } } //selector由ajax后期生成,所以其需要动态绑定click事件 $(container).on("click", selector, function(e){ if(e.currentTarget.tagName.toUpperCase() !== 'A') throw "$.fn.pjax or $.pjax.click requires an anchor element"; //鼠标中键点击,cmd/ctrl/shift/alt点击,在新标签页打开链接 //Middle click, cmd click, and ctrl click should open links in a new tab as normal. if( e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey ) return; //忽略跨域链接 if( location.protocol !== e.currentTarget.protocol || location.hostname !== e.currentTarget.hostname ) return; //忽略在当前页上的锚点链接 if( e.currentTarget.href.indexOf("#") > -1 && e.currentTarget.href.replace(/#.*/, "") == location.href.replace(/#.*/, "") ) return; //忽略已经被默认禁止的事件 if(e.isDefaultPrevented()) return; //用户点击页面链接时改变地址栏(URL)并写入历史记录以及AJAX加载页面 e.preventDefault(); var href = $(this).attr("href"); id = (new Date()).getTime(); history.pushState({href:href, id:id}, "", href); load(href); }); } }; })(jQuery);
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
自己想去尝试的时候。
到你自己懒得复制粘贴的时候就可以了。复制的复制的,你想给自己节约时间,然后你就发现,我把这些代码放在一个模块里,然后调用就可以了。
最简单的封装一个ajax
jQuery的Hello World插件还是很简单的.
下面是我总结的一个精简的jQuery PJAX插件: