简体   繁体   English

JavaScript:如何从链接的href解析命名锚?

[英]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. 当单击链接时,我想从链接的href解析命名的锚。 How can this be done? 如何才能做到这一点?

$(document).ready(function(){
    $('.my-links').click(function(e){
        var href = this.href; // http://example.com#myNamedAnchor
        // now parse out just 'myNamedAnchor'
    });
});
$(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 . JS小提琴演示

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 . JS小提琴演示

References: 参考文献:

You can get the anchor with this.hash . 您可以使用this.hash获得锚点。 To strip out the # , use this.hash.substr(1) . this.hash.substr(1) # ,请使用this.hash.substr(1)

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

See the MDN docs . 请参阅MDN文档

$(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. 查找哈希之后的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM