猿问

如何使用 history.pushState 将查询字符串变量附加到现有 URL?

我目前有一个显示我所有项目的 URL:

http://localhost:8090/projects.php

当我单击一个时,我可以使用以下简单代码将变量附加到 URL 的末尾:


$(document).ready(function() { 

$(".projects-container").on("click", ".procject-listing", function(){

  history.pushState({}, '', '?info='+$(this).attr("id"));

    $(".project-info").show(); 

          });

        });

URL 变为:

http://localhost:8090/projects.php/?info=23

完美运行。问题是,当我在“信息” div 中单击以打开另一张图片时,我希望单击功能将图片 ID 附加到 URL 的末尾:


$(document).ready(function() { 

$(".photo-block").on("click", ".photo", function(){

  history.pushState({}, '', '?photo='+$(this).attr("id"));

    $(".photo-viewer").show(); 

          });

        });

我希望得到一个看起来像这样的 url:

http://localhost:8090/projects.php/?info=23?photo=1

相反我得到了:

http://localhost:8090/projects.php/?photo=1

有没有办法附加到 URL 而不是覆盖“已经存在”的查询字符串变量?

我一直在看其他问题,但他们似乎没有解决我的问题。

谢谢!!


慕斯王
浏览 101回答 2
2回答

犯罪嫌疑人X

老大,在这里,解析当前的 URL 查询字符串,创建一个变量,然后将其添加到等式中。它是动态的,因为它的内容是基于点击的。$(document).ready(function() {&nbsp;&nbsp; $(".photo-block").on("click", ".photo", function(){&nbsp; &nbsp; function query_string(variable){&nbsp; &nbsp; &nbsp; &nbsp;var query = window.location.search.substring(1);&nbsp; &nbsp; &nbsp; &nbsp;var vars = query.split("&");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (var i=0;i<vars.length;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var pair = vars[i].split("=");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(pair[0] == variable){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return pair[1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}return(false);}&nbsp;&nbsp; &nbsp; &nbsp;history.pushState({}, '','?info=' + info +'?photo='+$(this).attr("id"));&nbsp; &nbsp; &nbsp;$(".photo-viewer").show();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });

慕少森

如果您想要多个查询字符串变量,则需要将它们与&.&nbsp;因此 ->&nbsp;projects.php?firstVar=1&secondVar=2。或者,您也可以使用#不需要推送状态的哈希,而只需将图片包装在普通锚点中,例如projects.php/?info=23#photo1.&nbsp;当用户点击img时,url会改变
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答