2012-04-24 71 views
1

即時通訊使用哈希變化下面的例子:jQuery中的hashchange?

$(window).trigger('hashchange'); 

$('.navBtn').bind('hashchange',function(){ 
    var hval = location.hash.slice(1); // remove the leading # 
    alert(hval); 
}); 

但好像沒有任何反應,我沒有得到任何警告。任何想法爲什麼?

回答

5

你只需要

//the js 
$(window).bind('hashchange',function(){ 
    var hval = location.hash.slice(1); // remove the leading # 
    alert(hval); 
}); 

<!--the html--> 
<a href="#imTheHash">Click me</a> 

哈希改變事件的窗口發射。沒有需要改變哈希值的js。這是處理的瀏覽器。即點擊鏈接將改變散列,然後窗口事件'hashchange'將被觸發。

0

Hashchange發生在window對象上。 $('.navBtn').bind('hashchange', ...)意味着什麼?

+0

url a href「/ something#home」,然後jquery將得到散列 – panthro 2012-04-24 16:14:11

+0

你的導航按鈕應該只設置散列,即'href =「#home」',然後'hashchange'將出現在'window'上。你應該在窗口對象上監聽hashchange事件。 – 2012-04-24 16:18:00

1

在綁定處理程序之前觸發事件。顛倒訂單並再試一次?

另外,我不確定,但是您在窗口元素上觸發事件,但將它綁定到一組子元素上。我不知道如何工作。

1

你必須:

  1. 逆順序爲:BIND然後觸發,當你在一個導航按鈕,點擊它會加載
  2. 使用相同的選擇

    $(window).bind('hashchange',function(){ 
        var hval = location.hash.slice(1); // remove the leading # 
        alert(hval); 
    }); 
    $(window).trigger('hashchange');