简体   繁体   中英

Updating a jump links href on click

I'm trying to update a jump links href on click. I set the initial jump link to something like this:

<a href="#2" id="next">Next</a>

Then I use a little JavaScript to update the href onclick:

var jump = this.href.match(/\#\d+$/)[0];
var num = parseInt(jump.substr(1, jump.length), 10);
var newNum = num + 1;

document.getElementById('next').href = '#' + num;

For some reason, when I click the jump link the first time, it takes me to #3 (instead of the expected #2). If I change the href in the HTML to #1, it will take me to #2, which seems counter intuitive. I guess my question is, is the jump happening after the href gets updated by JavaScript (it appears to be)? And how can I get it to jump first, then update the href?

(Also, I'm using addEventListener() to trigger the click).

var jump = this.href.match(/\#\d+$/)[0];
var num = parseInt(jump.substr(1, jump.length), 10);
var newNum = num + 1;

setTimeout(function() {
    document.getElementById('next').href = '#' + newNum;
});

Small refactoring:

var num = parseInt(this.href.split('#').pop(), 10);
var a = this;

setTimeout(function() {
    a.href = '#' + (num + 1);
});

the problem you are having is most likely because the jump is happening before the event is triggered, as you guessed, and this is causing this to be the new link, you can check it with a console.log(this) , a suggestion in this case will be to use event.preventDefault(); on the event, this will not make the link work and your code will run first. and just to make sure, you add the prevention in your event listener like this:

something.addEventListener("click", function(event) {
  event.preventDefault();}, false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM