Catching in page links with jQuery
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();
}
});
精彩评论