jQuery UI官网所使用的AJAX页面转换,代码分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | // AJAX读取页面内容,并把BODY内容以外的数据删除,重写到指定DIV function loadDemo(path) { $.get(path, function (data) { data = data.replace(/<script.*>.*<\/script>/ig, "" ); // Remove script tags data = data.replace(/<\/?link.*>/ig, "" ); //Remove link tags data = data.replace(/<\/?html.*>/ig, "" ); //Remove html tag data = data.replace(/<\/?body.*>/ig, "" ); //Remove body tag data = data.replace(/<head>.*<\/head>/ig, "" ); data = data.replace(/<\/?head.*>/ig, "" ); //Remove head tag data = data.replace(/<\/?!doctype.*>/ig, "" ); //Remove doctype data = data.replace(/<title.*>.*<\/title>/ig, "" ); // Remove title tags data = data.replace(/<meta.*>/ig, "" ); data = $.trim(data); $( 'style.demo-style' ).remove(); $( '#demo-frame' ).empty().html(data); $( '#demo-frame style' ).appendTo( 'head' ).addClass( 'demo-style' ); $( '#demo-link a' ).attr( 'href' , path); }); } $(document).ready( function () { //Rewrite and prepare links of right-hand sub navigation //重写菜单部分,处理菜单点击事件,点击后会跟据href提取内容并重写到指定DIV上 $( '#demo-config-menu a' ).each( function () { $( this ).attr( 'target' , 'demo-frame' ); $( this ).click( function (e) { //更新菜单按钮的class,实现按钮高亮 $( this ).parents( 'ul' ).find( 'li' ).removeClass( 'demo-config-on' ); $( this ).parent().addClass( 'demo-config-on' ); //Set the hash to the actual page without ".html" //重写地址栏,hash为#后面的字串 window.location.hash = this .getAttribute( 'href' ).match((/\/([^\/\\]+)\.html/))[1]; loadDemo( this .getAttribute( 'href' )); //默认点击事件实现 e.preventDefault(); }); }); //If a hash is available, select the right-hand menu item and load it if (window.location.hash) { loadHash(); } }); // 截入页面后,检查地址的hash是否与菜单中的链接一致,如果一致直接重写DIV。实现了能通过直接地址访问方式来访问AJAX行为所显示的内容 function loadHash() { $( '#demo-config-menu a' ).each( function () { if ( this .getAttribute( 'href' ).indexOf( '/' +window.location.hash.substr(1)+ '.html' ) != -1) { // 高亮 $( this ).parents( 'ul' ).find( 'li' ).removeClass( 'demo-config-on' ); $( this ).parent().addClass( 'demo-config-on' ); loadDemo( this .getAttribute( 'href' )); } }); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步