0

有什么方法可以使用 jquery 来捕获所有/任何哈希标签(#xxxxx)点击?不能把它们归为一类。

4

3 回答 3

3

下面的代码会做:

$('a[href*=#]').click( function() { /* do something */ } );

或者您可以使用 JamWaffles 指出的更有效的方法:

$('body').on('click', 'a[href*=#]', function() { /* do something */ });

编辑:

如果你想在页面加载 #hash in url 时做一些事情,那么你需要看看Ben Alman 的 jQuery hashchange 插件

这是您基本上需要添加到页面的一段代码(在这种特殊情况下不需要上面的代码)

$(document).ready( function() {
   $(window).hashchange( function(){
        // Alerts every time the hash changes!
        alert( location.hash );  
    })
    if( location.href.indexOf('#') > -1 )
    {
        $(window).trigger('hashchange'); // this will trigger the first time the page is loaded if there is a hash in your url
    }
});
于 2012-08-06T05:49:20.540 回答
0
$("a").each(function() {
    if ($(this).attr("href").indexOf("#") > -1) {
        $(this).bind("click", hashListener);
        // where hashListener is the name of your
        // tracking function.
    }
});
于 2012-08-06T05:50:31.913 回答
0
$('a').click(function(){
  if($(this).attr('href').indexOf('#') == 0 || $(this).attr('href').indexOf(window.location.href+"#") == 0){
    // do your stuff here.
  }
});

此代码同时处理相对和绝对哈希标记。

于 2012-08-06T05:50:40.040 回答