javascript - javascript variable shows in console.log but not in browser output
问题描述
I am trying to reuse the output of the year variable. I will need to reuse the updated value [based on hashchange] in multiple functions later on. It displays the correct value in the browser console, but it doesn't display in the browser.
<html>
<body>
<p></p>
<a href="#2018-01">1</a>
<a href="#2018-02">2</a>
</body>
<script>
location.hash = '#2019';
showHash();
var p = document.querySelector('p');
p.innerHTML = window.year;
function showHash() {
return year = location.hash;
}
window.onhashchange = showHash;
</script>
</html>
解决方案
By assigning location.hash
to year
you are not modifying p.innerHTML
. year
and p.innerHTML
are not referencing each other's value. When you initialised as follows:
p.innerHTML = window.year;
The value of year
was copied so now you have two values which happen to be the same at that moment, but they are not linked so that if you would assign a new value to the one, it would also update the other. No, they are not references.
So in the event handler you should also assign the new hash to p.innerHTML
, or better -- as the hash is text -- assign it to p.textContent
:
var p = document.querySelector('p');
var year;
function showHash() {
// Assign both to textContent and year (they are independent)
p.textContent = year = location.hash;
// Maybe call some other functions which need to know about `year`
manage();
}
function manage() {
console.log(year);
// ... etc
}
window.onhashchange = showHash;
location.hash = '#2019'; // This triggers showHash, no need to call it explicitly
<p></p>
<a href="#2018-01">1</a>
<a href="#2018-02">2</a>
推荐阅读
- r - R 神经网络使用起始公式向列添加权重
- jquery - jquery 数组并以自定义格式显示
- python - 使用 tkinter 复选框为 folium 选择数据帧
- javascript - 如何使用 Typescript 正确设置 axios 客户端?
- automation - 如何自动制作自动热键类型
- html - 基本 HTML 格式
- angular - 使用 Angular 中的 observable 调用登录 Web 服务
- azure - 在 Azure 中使用 IP 设置应用程序的最佳方式
- flutter - Flutter Provider.of
(...) 返回空值 - r - 具有滞后效应/交互作用的线性回归模型