首页 > 解决方案 > FadeIN FadeOUT 页​​面转换 javascript bug

问题描述

当我单击任何链接以将我带到新的 HTML 页面时,javascript 会将我路由到相同的 HTML 页面,而不是每个链接单独的 href。

这是我的代码

$(document).ready(function() {
  $('body').css('display', 'none');
  $('body').fadeIn(1000);
  $('.link').click(function(event) {
    event.preventDefault();
    newLocation = $('.link a').attr("href");
    $('body').fadeOut(1000, newpage);
  });
  function newpage() {
    window.location = newLocation;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>

我的目标是加载页面 FadeIN 并在单击链接时 FadeOUT,我得到了我想要的效果,但我只是不确定链接的这个问题是什么 - 有人知道吗?

标签: javascriptjqueryhtml

解决方案


正如@Taplar 所说,当您从链接中获取位置时href,您没有得到正确的位置。您只需获取文档中的第一个链接并查看其href属性。

您可以通过替换它来轻松解决这个问题(它会在文档中查找与link该类具有祖先的所有锚元素,然后返回它找到的第一个元素):

newLocation = $('.link a').attr('href');

有了这个(它找到所有锚元素作为任何元素的子元素,点击处理程序注册被点击):

newLocation = $(event.currentTarget).find('a').attr('href');

您正在做的另一件事很棘手,但不一定会破坏任何东西,它依赖于在处理程序和函数newLocation之间正确共享。相反,我建议您将参数显式传递给 newpage 以便它更可重用,并且您可以确定值的来源。clicknewpage

你可以在下面看到这个工作。

$(document).ready(function() {
  $('body').css('display', 'none');
  $('body').fadeIn(1000);
  $('.link').click(function(event) {
    event.preventDefault();
    newLocation = $(event.currentTarget).find('a').attr('href');
    // Pass anonymous function to fadeOut that calls newpage with newLocation
    $('body').fadeOut(1000, function () { newpage(newLocation); });
  });
  // newpage now accepts a parameter and uses it
  function newpage(location) {
    // Print to console so you can see what URL is getting used
    // You'll always get 404 using StackOverflow's UI since they don't have the relevant pages
    console.log(location);
    window.location = location;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link"><a href="pages/music/index.html">Music</a></div>
<div id="exhibition" class="link"><a href="pages/exhibition/index.html">Exhibition</a></div>
<div id="contact" class="link"><a href="pages/contact/index.html">Contact</a></div>
<div id="about" class="link"><a href="pages/about/index.html">About</a></div>


推荐阅读