如何引用磅符号(#)的jQuery的?符号、jQuery

2023-09-10 18:00:03 作者:物极必反

我一直在尝试一种新的方式使用jQuery动态获取内容的链接被点击的时候建立了一个网站。这里是jQuery的code:

I've been trying a new way to set up a website using jQuery to dynamically get the content when a link is clicked. Here is the jQuery code:

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

});

我一直在做这样说,因为我有我的网站,我要玩所有的时间,而不是每次点击一个链接时开始在背景的歌曲。

I've been doing it this way since I have a song in the background of my site that I want to play all the time and not start over every time a link is clicked.

整个事情的作品pretty的不错,除了2个问题我有。

The whole thing works pretty good, except for 2 issues I'm having.

比方说,我点击与我们联系链接。现在我看到#contactus在URL的末尾。如果我再刷新页面,我再次看到我的主页内容。 如果我尝试连接有人到我的联系我们页面同样的问题。 Let's say I click the contact us link. I would now see #contactus at the end of the url. If I then refresh the page, I see my home page content again. Same problem if I try linking someone to my contact us page.

我在想,如果jQuery的能以某种方式找出什么来了#号在URL后。在这种情况下,我可以改变我的jQuery的code中的最后一行来加载,而不是家庭的数据,所有的时间。

I was wondering if jQuery can somehow find out what comes after the # sign in the url. In that case, I can change the last line of my jQuery code to load that instead of the home data all the time.

推荐答案

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

window.location.hash will contain the value after the hash (if there is one). (This is when there's a hash in the current url, eg. current page, in the browser's address bar.)

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

Otherwise, if you're reading a link from an href, you'll need to use indexOf('#') and a bit of parsing.