FadeIN FadeOUT页面转换javascript bug

时间:2018-05-18 16:11:36

标签: javascript jquery html

当我点击我的任何链接将我带到一个新的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>

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

1 个答案:

答案 0 :(得分:0)

正如@Taplar所说,当你从链接的href中获取位置时,你找不到合适的位置。您只需获取文档中的第一个链接并查看其href属性。

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

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

with this(查找所有锚元素作为已点击点击处理程序的任何元素的子元素):

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

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

你可以在下面看到这个。

$(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>

相关问题