如何在jQuery中引用井号(#)?

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. 假设我点击“联系我们”链接。现在,我会在url的末尾看到#contactus。如果我刷新页面,我会再次看到我的主页内容。
  2. 如果我试图将某人链接到我的联系我们页面,则会出现相同的问题。

我想知道jQuery是否可以找出url中#符号后面的内容。如果可以,我可以将jQuery代码的最后一行更改为始终加载该内容,而不是始终加载主页数据。


2
可能重复:https://dev59.com/7nVC5IYBdhLWcg3wbgdT - Marek
1
你在标记上添加了无效的属性?..不好哦.. ;) - Reigel Gallarde
如果您想将一些任意数据存储到元素中,请尝试使用 .data(),我同意 Reigel 的观点。 - ZX12R
谢谢,我已经摆脱了那些数据属性,虽然我知道它们是HTML5的一部分:http://ejohn.org/blog/html-5-data-attributes/ - Justin
2个回答

3

window.location.hash将包含#后面的值(如果有的话)。(当当前页面的浏览器地址栏中有#时,如当前url中有#)

否则,如果你正在阅读来自href的链接,你需要使用indexOf('#')和一些解析。


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');

    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接