问题描述
我在使用 jQuery 以及如何动态处理 url 时遇到问题.如果我有一个带有链接的页面并且每个页面都有一个 id 来调用一个函数和一个 id,那么我想要做的是.如何更改特定链接的 url 并将该 url 用作书签.下面是我的代码
<div data-role="header"><h1>列表</h1><div data-role="内容"><ul data-role="listview" id="carlist"><li><a href="#" onclick="cardtails('1')">讴歌</a></li><li><a href="#" onclick="cardtails('2')>奥迪</a></li><li><a href="#" onclick="cardtails('3')>BMW</a></li>
<div data-role="footer"><h4>页脚</h4>
因此,当您单击列表中的汽车时,参数为 1 的名为 cardetails 的函数将返回服务器并获取 id=1 的汽车的 cardetails.我的问题不是,但是当 JSON 数据返回时,我希望 url 更改为 cardtails#1 或类似的内容.因此,它可以识别用户在哪里,浏览器可以将其添加到其历史记录中,如果用户将 url 加入书签,浏览器将能够找到显示相同数据的确切页面.
解决方案本示例使用 jQM changePage()
发送带有 Ajax 页面请求的数据.仅当 changePage()
的to"参数是 URL 时才能使用它.查看 jQM 文档了解更多信息.
测试示例的说明:
创建文件夹在文件夹内创建一个名为cars.js的文件在文件夹内创建一个名为cars.html的文件在文件夹内创建一个名为 car-details.html 的文件用您可以在下面找到的相应代码填充每个文件打开cars.html,这是第一页并导航在 car.js 文件中添加以下代码:
$(document).on( "pageinit", "#car-page", function( e ) {$('#car-list a').on('click', function(e) {e.preventDefault();$.mobile.changePage('car-details.html', {数据: {id:this.id}});});});$(document).on( "pageinit", "#car-details-page", function( e ) {var passId = (($(this).data("url").indexOf("?") > 0) ? $(this).data("url") : window.location.href ).replace(/.*id=/, "" );$("#details").html(["Selected id is: '", passId, "'"].join(""));});
在cars.html页面中添加以下代码.
<html lang="zh-cn"><头><title>汽车示例</title><link rel="stylesheet" href="http://code.jquery/mobile/1.3.0/jquery.mobile-1.3.0.min.css"/><script src="http://code.jquery/jquery-1.8.2.min.js"></script><script src="http://code.jquery/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script><script src="./cars.js"></script>头部><身体><div id="car-page" data-role="page"><div data-role="header"><h1><a data-ajax="false" href="/">汽车列表</a></h1><div data-role="内容"><ul data-role="listview" id="car-list"><li><a href="#" data-transition="flip" id="acura">讴歌</a></li><li><a href="#" data-transition="flip" id="audi">奥迪</a></li><li><a href="#" data-transition="flip" id="bmw">BMW</a></li>