在绑定事件之间传递参数

时间:2012-10-19 06:24:24

标签: javascript jquery

假设我有两个绑定事件 - 按照下面的点击和散列更改(超简化示例):

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

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

如何将提升click事件的元素的id传递给bound hashchange事件? 我见过类似下面的例子,但是不能让它起作用:

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

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

任何建议都会很棒......

1 个答案:

答案 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
}