简体   繁体   English

e.preventDefault() 之后的链接不会加载,没有 jQuery

[英]The link after e.preventDefault() doesn't load, without jQuery

I want to load a link on click, but it doesn't load.我想在点击时加载一个链接,但它没有加载。 I use preventDefault() to load the animation and setTimeout() .我使用preventDefault()加载动画和setTimeout() What else should I use?我还应该使用什么?

I try return true , and think to save the path link of the node in a variable and then using location.href to call it.我尝试return true ,并认为将节点的路径链接保存在一个变量中,然后使用location.href来调用它。 But I don't know how to do it.但我不知道该怎么做。

<div class="content animated fadeInDown"> Table </div>

<td>
    <a class="link" href="./pizzerias/lazzaroni.html">See More</a>
</td>

<script>
let links = document.querySelectorAll('.link');

links.forEach((link)=>{
    link.addEventListener('click', (e)=>{

        e.preventDefault();
        let content = document.querySelector('.content');

        content.classList.remove('fadeInDown');
        content.classList.remove('animated');

        content.classList.add('fadeOutUp');
        content.classList.add('animated');

        setTimeout(500);
    });
});
</script>

preventDefault is doing exactly what the name implies. preventDefault正是顾名思义。 It prevents the default behavior of an event.它可以防止事件的默认行为。

In the case of a link, the default behavior is to redirect the user to the associated href attribute value.在链接的情况下,默认行为是将用户重定向到关联的href属性值。

You are preventing this from happening.您正在阻止这种情况发生。 So it is never going to happen.所以它永远不会发生。 The setTimeout isn't doing anything either as it is. setTimeout也没有做任何事情。

If you want to redirect the user after the animation you need to do it explicitely:如果你想在动画之后重定向用户,你需要明确地做:

links.forEach((link)=>{
    link.addEventListener('click', (e)=>{

        e.preventDefault();
        let content = document.querySelector('.content');

        content.classList.remove('fadeInDown');
        content.classList.remove('animated');

        content.classList.add('fadeOutUp');
        content.classList.add('animated');

        setTimeout(() => {
            window.location.href = e.target.href;
        }, 500);
});

setTimeout() require a callback function as its first argument but you only pass the time. setTimeout()需要一个回调函数作为它的第一个参数,但你只是传递时间。 It would be这将是

setTimeout(() => {
    window.location.href = e.target.href
}, 500)

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

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