2015-07-20 71 views
0

一個網頁有一些鏈接:jQuery:如何在hashchange事件處理程序中查找元素?

<a href="#example-hash-1" class="link">example-1</a> 
<a href="#example-hash-2" class="link">example-2</a> 
<a href="#example-hash-n" class="link">example-n</a> 

點擊任何對他們的運行hashchange的情況下,我們要處理:

$(window).on('hashchange', function(event){ 

    // Is it possible (inside this handler) to find out which of a.link was clicked? 

}); 

或者,有另一種方式來做到這一點?

+0

爲你的情況[event.target](https://api.jquery.com/event.target/)將做到這一點。 –

+0

和'location.hash;'?即:'var hash = location.hash;' –

回答

0

我認爲你可以使用onclick作爲標籤中的一個屬性,或者你可以通過jQuery使用.click()事件。我認爲這將實現與hashchange上的窗口相同的功能。

0

event.target將持有哪個元素觸發事件。

我目前無法檢查,但我認爲this也綁定。

0

試試這個:

$(window).on('hashchange', function(event){ 

    var hash = location.hash; 
    var $this = $(hash); 
    alert($this.html()); 
}); 
0

雖然我認爲增加點擊聽衆實際的鏈接將是最好的,你也可以搜索,將已經改變了哈希這樣的元素:

$(window).on('hashchange', function(event){ 
    $('a[href$='+window.location.hash+']').action(); 
}); 
相關問題