简体   繁体   English

Javascript页面过渡未定义

[英]Javascript page transition undefined

I'm trying to add page transition to my website. 我正在尝试将页面转换添加到我的网站。 But for some reason when I click on a link it redirects to mywebsite.com/undefined 但是由于某些原因,当我单击链接时,它会重定向到mywebsite.com/undefined

This is the code I'm using 这是我正在使用的代码

jQuery(document).ready(function($) {
  $('.menu-item').click(function(event) {
    event.preventDefault();
    newLocation = this.href;
    $('.preloader').fadeIn(1000, newpage);
  });

  function newpage() {
    window.location = newLocation;
  }
});

I can't get it to work. 我无法正常工作。 Any help would be appreciated. 任何帮助,将不胜感激。

That's because newLocation is out of scope (it is only available in the click function's scope). 这是因为newLocation不在范围内(仅在click函数的范围内可用)。 (See Update 1.) (请参阅更新1。)

Instead, pass it into the newPage function like so: 而是将其传递给newPage函数,如下所示:

jQuery(document).ready(function($) {
  $('.menu-item').click(function(event) {
    event.preventDefault();

    $('.preloader').fadeIn(1000, function() {
        // Pass this.href into the newPage function
        newPage(this.href);
    });
  });

  function newPage(newLocation) {
    window.location = newLocation;
  }
});

Notes: 笔记:

  • Notice that I am passing a function as the second argument to the .fadeIn function. 注意,我将一个函数作为第二个参数传递给.fadeIn函数。 (See the API Docs .) You cannot just pass newPage(this.href) into the second argument because that will pass the return value of the newPage function (which is null) into the .fadeIn function. (请参阅API Docs 。)您不能仅将newPage(this.href)传递给第二个参数,因为这会将newPage函数的返回值 (为null) .fadeIn.fadeIn函数。
  • This pattern applies to other jQuery functions such as .slideUp . 此模式适用于其他jQuery函数,例如.slideUp Here's an example of an implementation of .slideUp : 这是.slideUp的实现.slideUp

     $('.preloader').slideUp({ duration: 1000, easing: "easeInOutQuint" }, function() { newpage(this.href) }); 

Update 1: 更新1:

As noted by Barmar in the comments, since newLocation is not declared with var in your code snippet, it should automatically be a global variable. 正如Barmar在评论中指出的那样 ,由于newLocation没有在代码段中用var声明,因此它应该自动是一个全局变量。 As such, it should actually be in scope in the newpage function and the original snippet should actually work. 这样,它实际上应该在newpage函数的作用域内,并且原始代码段应该实际起作用。

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

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