jquery AJAX navigation特性

本文探讨了使用jQuery Mobile时遇到的问题:通过AJAX导航到第二个页面时,jQuery方法及CSS失效。文中详细解释了这一现象的原因,并提供了解决方案,即将依赖的脚本和样式直接写入data-role=page的元素内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     刚开始用jquery mobile,做页面用起来也挺顺手,特别是导航特别炫,可以用动画,不过刚开始用发现了一个问题,就是jquery的代码在original page的时候是好使的,但是当导航到第二个页面的时候,jquery的所有方法,和第二个页面的css全部失效。查了一下,原来是jquery mobile有一个特性就是ajax导航,下面是从官方文档摘录下来的一段话:

      Whenever a link is clicked or a form is submitted, that event is automatically intercepted by the AJAX nav system and is used to issue a AJAX request based on the href or form action instead of reloading the page. While the framework waits for the AJAX response, a loader overlay is displayed.

      When the requested page loads, the jQuery Mobile parses the document for an element with the data-role="page" attribute and inserts that code into the DOM of the original page. Next, any widgets in the incoming page are enhanced to apply all the styles and behavior.The rest of the incoming page is discarded so any scripts, stylesheets or other information in the will not be included. 

 

      原来jquery mobile在页面之间导航的时候是使用ajax加载,然后将目标页面中的第一个data-role=“page”的第一个div元素设置到original page中,目标页面中的其余部分全部“抛弃”,也就是说写在<head></head>标签中的script和style全部失效。从stackoverflow上找到了解决方法:用jquery mobile的标准写法,在链接,button中都加一个rel="external"属性,或则加上data-ajax="false"就能使得目标页面被完全重新加载。但是这样就无法实现动画效果了。

      既然jQuery mobile的ajax导航方式是选取目标页面的第一个data-role="page"的div用来替换当前页面的page,那么就将目标页面依赖的script和style都写到page里面,这样就能解决问题了。

      附上stackoverflow上的一个解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值