jQuery get hash of <a> element using .on() event

空扰寡人 提交于 2019-11-29 09:53:04

Your a element doesn't have a hash attribute. try getting the href attribute and using javascript's substr and indexOf functions to split the string at the #

var href = $(this).attr("href");
var hash = href.substr(href.indexOf("#"));

You can also use

$(this).prop("hash");
$('a.js-hash').click(function() {

    // Store hash
    var hash = this.hash;

    // Using jQuery's animate() method to add smooth page scroll
    $('html, body').animate({
        scrollTop: $(hash).offset().top
    }, 1000, function() {

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
    });

    // Prevent default anchor click behavior
    return false;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!