开发者

Catching in page links with jQuery

开发者 https://www.devze.com 2022-12-19 03:48 出处:网络
Hi i want to trig a function when user click in page links for example abc.com/hello.html#variable1 i w开发者_JAVA百科ant to catch #varible1 and execute a function.If you want to grab the string after

Hi i want to trig a function when user click in page links for example abc.com/hello.html#variable1 i w开发者_JAVA百科ant to catch #varible1 and execute a function.


If you want to grab the string after the hash:

$("a[href*='#']").click(function() {
    var hash = this.href.replace(/.*#(.*)$/, '$1');
    // do something
    return false
});


Capture the hash and substring it out:

$("a[href*='#']").click(function(e){
  var hash = $(this).attr('href').substring($(this).attr('href').indexOf("#"));
  //hash = #var
  function(hash);
});


To attach logic to all hash-links, you can do the following:

$("a[href^='#']").click(function(e){
  // user clicked an inpage link
});


If you want to trigger a function for links with hashes that are dynamically inserted, use this:

$(document).click(function (event) {
    var target = $(event.target);
    if (target.filter("a[href*='#']").size() > 0) {
        var hash = target.attr("hash");

        // Do something with hash.

        event.preventDefault();
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消