I have 2 html pages. The first page holds the links and once the user clicks on one link, then it redirects to the second page. What I am trying to achieve though is to have the href value at the top of the second page once the user clicks one of the links.
At the moment, I have a function that gets the href value, but when I go to the second page I get an error on the console "Cannot read property href of null".
What am I missing to get this behaviour? I enclose my code for more information
The html for the link (Link.html)
<body>
<a href="ApplicationForm.html" id="linkId" onclick="getLinkValue()">Link</a>
</body>
The script that gets the href value (AppInit.js)
function getLinkValue() {
var linkValue = document.getElementById("linkId").href;
return linkValue;
};
The html page that the href value should be displayed(ApplicationForm.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>
The script that is supposed to get the link value from AppInit (This is a different js file)
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();
};
答案 0 :(得分:1)
您似乎认为变量 linkValue 中的第二步中存储的值可以在导航后的后续步骤中检索,但情况并非如此。
JavaScript变量仅在网页的生命周期内保留其值。导航到另一个页面后,再次从头开始。
要保留值,您需要在通过URL参数(或POST)导航时传递它们,或者保留它们(cookies, localStorage ,...)。
在您的情况下,我会建议网址参数:
Link.html
添加需要名称(例如 arg )和值(例如 ApplicationForm )的网址参数:
<body>
<a href="ApplicationForm.html?arg=ApplicationForm">
Link
</a>
</body>
ApplicationForm.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>