0

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>
4

1 回答 1

1

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>

于 2019-01-19T19:52:22.650 回答