将 href 值从 <a> 标记链接到另一个 html 页面
Linking the href value from an <a> tag to another html page
我有2个html页面。第一页包含链接,一旦用户单击一个链接,它就会重定向到第二页。我试图实现的是,一旦用户单击其中一个链接,将 href 值放在第二页的顶部。
目前,我有一个获取 href 值的函数,但是当我转到第二页时,我在控制台上收到错误"无法读取 null 的属性 href"。
我缺少什么才能获得这种行为?我附上我的代码以获取更多信息
- 链接
的 html (链接.html(
<body> <a href="ApplicationForm.html" id="linkId" onclick="getLinkValue()">Link</a> </body>
获取 href 值的脚本 (AppInit.js(
function getLinkValue() { var linkValue = document.getElementById("linkId").href; return linkValue; };
应显示 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>
应该从 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 参数:
-
链接.html
添加一个需要名称(例如arg(和值(例如ApplicationForm(的URL参数:
<body> <a href="ApplicationForm.html?arg=ApplicationForm"> Link </a> </body>
-
申请表.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>
相关文章:
- 如何使用jQuery自动打开页面上的所有链接
- 制作一个不带HTML a标记但在动画播放完毕后指向其他页面的超链接
- 单击页面上的链接后高度发生变化
- 加载超链接页面后如何响应事件
- 如何使用嵌套的 React 组件从“链接页面”的顶部开始
- 使用phonegap在jquery-mobile中链接页面/加载javascript的最佳实践是什么
- 链接页面时出错
- Rails 4涡轮链接页面:用JS加载
- 使用jQuery Mobile链接页面和加载JavaScript
- Javascript-href操作在链接页面上执行
- Chrome动画链接页面加载
- 在页面完全加载后重定向到链接页面
- 链接页面上的菜单没有关闭
- jQuery fade "back to top"链接.页面加载链接可见性
- 如何将链接页面显示为表格的内容
这就是我的例子 - 当链接页面加载时,使用jQuery/Javascript从外部链接应用过滤功能
- 如果javascript被禁用,则移动链接页面或显示弹出窗口
- 如何有条件地阻止锚点跳转到其链接页面
- 改变颜色当前链接页面角&css
- 如何使锚链接页面可滑动