简体   繁体   English

点击时更新跳转链接href

[英]Updating a jump links href on click

I'm trying to update a jump links href on click. 我正在尝试在点击时更新跳转链接href。 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: 然后,我使用一些JavaScript来更新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). 由于某种原因,当我第一次单击跳转链接时,它将带我到#3(而不是预期的#2)。 If I change the href in the HTML to #1, it will take me to #2, which seems counter intuitive. 如果将HTML中的href更改为#1,它将带我进入#2,这似乎与直觉相反。 I guess my question is, is the jump happening after the href gets updated by JavaScript (it appears to be)? 我想我的问题是,在href由JavaScript更新后(似乎是)会发生跳转吗? And how can I get it to jump first, then update the href? 以及如何让它先跳转然后更新href?

(Also, I'm using addEventListener() to trigger the click). (此外,我正在使用addEventListener()来触发点击)。

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(); 您所遇到的问题很可能是因为如您所猜想的那样,是在触发事件之前发生了跳转,并且这导致this是新链接,您可以使用console.log(this)进行检查,这种情况将使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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