2010-10-10 48 views
2

我想如果我可以点击类“查询”的链接,并有它的id属性后面的哈希。例如,一个链接,看起来像这样:jquery - 设置哈希后的网址

<a href="#" id="members" class="query">Members</a>

点击时会网址更改从example.com/usersexample.com/users#members

这里是我到目前为止的代码:

$('.query').click(function(event){ 
    event.preventDefault(); 
    window.location.href = $(this).attr('id'); 
}); 

眼下点击链接只是移动网址example.com/members

回答

8

设置hash属性:

window.location.hash = $(this).attr('id'); 
2

尝试window.location.hash代替window.location.href

3

让id属性来自散列不是很愚蠢吗?为什么不只是......这样做不合理吗?无论如何,你可以这样做:

$(".query").click(function() { 
    window.location.hash = this.id; 
    return false; // prevent default link follow 
});