2010-10-10 41 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 
});