javascript 动画结束时导航到 href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15469687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:52:16  来源:igfitidea点击:

Navigate to href when animation ends

javascriptjquery

提问by Richard Denton

So i'm trying to make a section fade out before following a link like so

所以我试图在跟随这样的链接之前让一个部分淡出

<a class="fadelink" href="path/to/file">Hello</a>

<script type="text/javascript">
        $("a.fadelink").click(function(e){
            e.preventDefault();         
            $("#content").fadeTo(400,0,function(){
                window.location.href = $(this).attr("href");

            });
        });
    </script>

Problem is, jQuery keeps returning me with "undefined" and 404's the redirect.

问题是,jQuery 不断以“未定义”和 404 的重定向返回我。

回答by Roko C. Buljan

Your $(this)in $(this).attr("href")is pointing to $("#content")which is wrong. Move it into the right scope:

你的$(this)in$(this).attr("href")指的是$("#content")哪个是错误的。将其移入正确的范围:

$("a.fadelink").on("click", function( evt ) {

   evt.preventDefault();   

   var goTo = $(this).attr("href");           // get href value of `this` anchor

   $("#content").fadeTo(400, 0, function() {
       window.location = goTo;                // Now you can use it
   });

});

回答by Asad Saeeduddin

You're referring to the wrong this. The hrefattribute is present on the anchor, not the #contentelement.

你指的是错误的this. 该href属性存在于锚点上,而不是#content元素上。

$("a.fadelink").click(function(e){
    e.preventDefault();
    var that = this;
    $("#content").fadeTo(400,0,function(){
        window.location.href = $(that).attr("href");

    });
});