(function($, undefined) { $.fn.subpage = function(options) { $(document).bind( "pagebeforeshow", function() { var forword = $.mobile.urlHistory.getNext(); if (forword) { var dataUrl = forword.url; var forwordPage=$.mobile.pageContainer .children(":jqmData(url='" + dataUrl + "')"); if(forwordPage){ forwordPage.remove(); } } $.mobile.urlHistory.clearForward(); }); }; $(document).bind("pagecreate create", function(e) { $(":jqmData(role='page')", e.target).subpage(); }); })(jQuery);
结果事与愿违,在页面返回时,出现了js脚本错误,如下图:
那么是什么原因呢?不在这个事件里做处理,那在哪里处理呢?于是我仔细研读了一下jQuery Mobile源码,发现了下面一段:
transitionPages( toPage, fromPage, settings.transition, settings.reverse ) .done(function() { removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } //remove initial build class (only present on first pageshow) $html.removeClass( "ui-mobile-rendering" ); releasePageTransitionLock(); // Let listeners know we're all done changing the current page. mpc.trigger( "pagechange", triggerData ); });
页面在切换完后,会触发pagechange事件,于是我把pagebeforeshow改成了pagechange,一切都按预期运行,并且没有错误,终于大功告成了。
总结
在使用该插件时,请注意以下几点: