3

我一直在尝试一种使用 jQuery 设置网站的新方法,以便在单击链接时动态获取内容。这是jQuery代码:

$(document).ready(function() {

 var content_loader = $('#content-loader');

 $('#nav ul li a').click(function () {
  $(this).closest('ul').find('li.active').removeClass('active');
  $(this).parent().addClass('active');
  content_loader.load('content/' + $(this).attr('data-name') + '.html'); 
  });

 content_loader.load('content/home.html');

});

我一直这样做,因为我的网站背景中有一首歌曲,我想一直播放,而不是每次点击链接时都重新开始。

整个事情都很好,除了我遇到的两个问题。

  1. 假设我点击了联系我们链接。我现在会在网址末尾看到#contactus。如果我然后刷新页面,我会再次看到我的主页内容。
  2. 如果我尝试将某人链接到我的联系我们页面,也会出现同样的问题。

我想知道 jQuery 是否可以以某种方式找出 url 中 # 符号之后的内容。在这种情况下,我可以更改我的 jQuery 代码的最后一行以始终加载它而不是 home 数据。

4

2 回答 2

3

window.location.hash将包含哈希后的值(如果有的话)。 (这是当当前 url 中有一个哈希值时,例如当前页面,在浏览器的地址栏中。)

否则,如果您正在从 href 读取链接,则需要使用indexOf('#')并进行一些解析。

于 2010-07-01T07:44:05.020 回答
2

谢谢你们的回答。这就是我现在的做法:

$(document).ready(function() {

    var content_loader = $('#content-loader');

    $('#nav ul li a').click(function () {
        $(this).closest('ul').find('li.active').removeClass('active');
        $(this).parent().addClass('active');
        content_loader.load('content/' + $(this).attr('href').slice(1) + '.html');  
        });

    var initial = 'home';
    if (window.location.hash) {
        initial = window.location.hash.slice(1);
        }

    $('#nav').find('a[href="#' + initial + '"]').parent('li').addClass('active');
    content_loader.load('content/' + initial + '.html');

    });
于 2010-07-01T08:14:11.013 回答