JavaScript在页面更改时保留URL参数

问题描述 投票:0回答:2

我正在使用Vanilla Javascript,

我有两个页面,page01.htmlpage02.html这些页面共享相同的导航系统。

我想将参数加载到page01的URL中,然后在导航上单击page02后,page02将在其URL中加载该参数。

示例:

  1. 我在page01.html
  2. 我将参数加载到URL中,所以现在有了page01.html /?param = X
  3. 我单击菜单项page02
  4. 我要加载page02.html /?param = X

没有使用localStorage和sessionStorage的方法吗?

javascript query-string window.location
2个回答
1
投票

这是使用原始JavaScript的简单解决方案:

Page01.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>

<div>Page 1</div>

<a href="page02.html">go to page 2</a>

<script>
   var linkToPage2 = document.querySelector("a[href='page02.html']");
   linkToPage2.addEventListener("click", function(e){
   e.preventDefault();
     if(location.search){
       window.location.href = "page02.html" + location.search; 
     }
 });

</script>
</body>
</html>

Page02.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>

<div>Page 2</div>

<a href="page01.html">go to page 1</a>

<script>
    var linkToPage1 = document.querySelector("a[href='page01.html']");
    linkToPage1.addEventListener("click", function(e){
     e.preventDefault();
        if(location.search){ 
             window.location.href = "page01.html" + location.search;
         }
     });
 </script>
 </body>
 </html>

0
投票

我同时使用了Bergi的评论和Henry的回答来创建自己的版本。

基本上,我只是在标签上创建了onclick="menuClick();"id="menuLink"。然后在Javascript上,我刚刚将location.search添加到了href:

menuClick = function() {
    document.getElementById('menuLink').href += location.search
  }
© www.soinside.com 2019 - 2024. All rights reserved.