如何避免点击链接而不删除“href”属性?

时间:2021-11-08 21:19:53

I need to delay a little bit redirection to a new page after clicking on certain links.

在点击某些链接后,我需要稍微延迟一点重新定向到新页面。

Right now I'm using following jQuery:

现在我使用以下jQuery:

$('.menu-element a').click(function(){
    var src = $(this).attr('href');
    $(this).removeAttr('href');             
    anim(src);
})

And it works fine. It runs really short animation and after that redirects to clicked page.

它工作正常。它运行很短的动画,然后重定向到点击页面。

But I would like to keep the href attribute of link (i.e. in case when someone clicks twice very fast).

但是我想保留link的href属性(例如,如果有人快速点击两次)。

when I add $(this).attr('href', src); at the end of code listed above, it doesn't wait for animation to finish only redirects to new page right after clicking on the link.

当我添加(美元)。attr(“href”、src);在上面列出的代码的末尾,它不等待动画完成,只需点击链接后重新定向到新的页面。

How can I preserve the href property and avoid the page being redirected to new address by it?

如何保存href属性并避免页面被它重定向到新地址?

2 个解决方案

#1


6  

add return false into your function. This prevents the browser following the link's href, and is then up to you to make that redirect in your javascript. e.g. by adding something to the end of your anim() function that updates the location.

在函数中添加return false。这可以防止浏览器跟随链接的href,然后由您在javascript中进行重定向。例如,在anim()函数的末尾添加一些东西来更新位置。

It also means you don't need to remove the href from the link.

这也意味着您不需要从链接中删除href。

$('.menu-element a').click(function(){
    var src = $(this).attr('href');
    anim(src);
    return false;
})

#2


4  

You can use event.preventDefault(). return false will also work, but it will also stop event bubbling (not a problem most of the time, you just should be aware of it).

您可以使用event.preventDefault()。返回false也会工作,但是它也会停止事件冒泡(大多数时候不是问题,您应该知道)。

$('.menu-element a').click(function(event){
    anim($(this).attr('href'));
    event.preventDefault();
})

#1


6  

add return false into your function. This prevents the browser following the link's href, and is then up to you to make that redirect in your javascript. e.g. by adding something to the end of your anim() function that updates the location.

在函数中添加return false。这可以防止浏览器跟随链接的href,然后由您在javascript中进行重定向。例如,在anim()函数的末尾添加一些东西来更新位置。

It also means you don't need to remove the href from the link.

这也意味着您不需要从链接中删除href。

$('.menu-element a').click(function(){
    var src = $(this).attr('href');
    anim(src);
    return false;
})

#2


4  

You can use event.preventDefault(). return false will also work, but it will also stop event bubbling (not a problem most of the time, you just should be aware of it).

您可以使用event.preventDefault()。返回false也会工作,但是它也会停止事件冒泡(大多数时候不是问题,您应该知道)。

$('.menu-element a').click(function(event){
    anim($(this).attr('href'));
    event.preventDefault();
})