将 href 值从 <a> 标记链接到另一个 html 页面

Linking the href value from an <a> tag to another html page

本文关键字:链接 页面 另一个 html 值从 href      更新时间:2023-09-26

我有2个html页面。第一页包含链接,一旦用户单击一个链接,它就会重定向到第二页。我试图实现的是,一旦用户单击其中一个链接,将 href 值放在第二页的顶部。

目前,我有一个获取 href 值的函数,但是当我转到第二页时,我在控制台上收到错误"无法读取 null 的属性 href"。

我缺少什么才能获得这种行为?我附上我的代码以获取更多信息

    链接
  1. 的 html (链接.html(

    <body>
        <a href="ApplicationForm.html" id="linkId" onclick="getLinkValue()">Link</a>
    </body>
    
  2. 获取 href 值的脚本 (AppInit.js(

     
        function getLinkValue() {
            var linkValue = document.getElementById("linkId").href;
            return linkValue;
        };
     
  3. 应显示 href 值的 html 页面(应用程序表单.html(

      <button type="button" name="button" onclick="displayLinkValue();">Get href value</button>
      <div id="container">
              <!-- The container that should include the href value from the previous page -->
      </div>
    
  4. 应该从 AppInit 获取链接值的脚本(这是一个不同的 js 文件(

    
    var script = document.createElement('script');
    script.src ="AppInit.js";
    document.getElementsByTagName('script')[0].parentNode.appendChild(script);
    function displayLinkValue() {
        var linkContainer = document.getElementById('container');
        linkContainer.innerHTML += getLinkValue();
    };
    

您似乎认为在变量 linkValue 中的步骤 2 中存储的值可以在导航后的后续步骤中检索,但事实并非如此。

JavaScript 变量仅在网页的生命周期内保留其值。导航到另一个页面后,您将再次从头开始。

要保留值,您需要在通过 URL 参数(或 POST(导航时传递它们,或者保留它们(cookie、localStorage 等(。

在您的情况下,我会建议 URL 参数:

  1. 链接.html

    添加一个需要名称(例如arg(和值(例如ApplicationForm(的URL参数:

    <body>
        <a href="ApplicationForm.html?arg=ApplicationForm">
           Link
        </a>
    </body>
    
  2. 申请表.html

    <div id="container"></div>
    <script>
    // function to get a particular argument from the URL
    function getUrlArg(name) {
        var res = location.search.substr(1).split("&").filter(function (item) {
            return item.indexOf(name + '=') === 0;
        }).pop();
        return res ? decodeURIComponent(res.substr(res.indexOf('=') + 1)) : '';
    }
    document.getElementById('container').textContent = getUrlArg('arg');
    </script>