[英]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 (See Update 1.) newLocation
is out of scope (it is only available in the click
function's scope). 这是因为
newLocation
不在范围内(仅在click
函数的范围内可用)。 (请参阅更新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: 笔记:
.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. 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.