开发者

JavaScript: How to parse the named anchor from the href of a link?

I would like to parse the named anchor from the href of a link when it is clicked. How can this be done?

$(document).ready(function(){
    $('.my-links').click(fu开发者_运维知识库nction(e){
        var href = this.href; // http://example.com#myNamedAnchor
        // now parse out just 'myNamedAnchor'
    });
});


You can get the anchor with this.hash. To strip out the #, use this.hash.substr(1).

$('.my-links').click(function(e){
    var hash = this.hash.substr(1); // myNamedAnchor
});

See the MDN docs.


$(document).ready(function(){
    $('.my-links').click(function(e){
        var href = this.href; // http://example.com#myNamedAnchor
        var hash = href.substr(href.indexOf('#'));
        alert(hash);
        return false;
    });
});

JS Fiddle demo.

If you don't want to include the # character, then amend the above to:

$(document).ready(function(){
    $('.my-links').click(function(e){
        var href = this.href; // http://example.com#myNamedAnchor
        var hash = href.substr(href.indexOf('#') + 1);
        alert(hash);
        return false;
    });
});

JS Fiddle demo.

References:

  • substr().
  • indexOf().


$(document).ready(function(){
    $('.my-links').click(function(e){
        var href = this.href; // http://example.com#myNamedAnchor
        var myNamedAnchor = href.match(/[^#]*$/);
    });
});

That'll do it.


I think you could do:

$('.my-links').click(function(e){
     //if  http://example.com#myNamedAnchor hash = myNamedAnchor 
     var hash=this.hash;        
});


Use

parsedHref = href.substr(href.indexOf("#")+1);

To find whatever is after the hash.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜