2012-10-19 196 views
1

说我有两个绑定事件 - 点击和hashchange按照以下(超简化的例子):传递参数

$('a').bind('click', function(e) { 
    location.hash = $(this).attr('id'); 
} 

$(window).bind('hashchange', function(e) { 
    console.log(e.target); 
} 

我将如何通过元素的提高点击事件ID绑定到hashchange事件? 我见过像下面的例子,但不能得到它的工作:

$('a').bind('click', ['some-data'], function(e) { 
    location.hash = $(this).attr('id'); 
} 

$(window).bind('hashchange', function(e) { 
    console.log(e.data[0]); 
} 

任何意见将是巨大的......

回答

0

这是不可能发现从发起哈希变化锚在hashchange事件处理程序中,因为事件是由window本身触发的。

hashchange处理程序中,您可以检查location.hash的值,因为您之前已使用location.hash = $(this).attr('id')将锚的ID放在那里。

$(window).bind('hashchange', function(e) { 
    console.log(location.hash.substr(1)); // should be the id of your anchor 
}