最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery hashchange event - where to place? - Stack Overflow

programmeradmin2浏览0评论

I am using JQuery hashchange event.

$(window).on('hashchange', function () {
//do something
});

When my url contains a hash during first time load I understand that this needs to be triggered with $(window).hashchange();

Can I place it inside document ready instead?

$(document).ready(function () {
    $(window).on('hashchange', function () {
    //do something
    });
});

I am using JQuery hashchange event.

$(window).on('hashchange', function () {
//do something
});

When my url contains a hash during first time load I understand that this needs to be triggered with $(window).hashchange();

Can I place it inside document ready instead?

$(document).ready(function () {
    $(window).on('hashchange', function () {
    //do something
    });
});
Share asked Oct 24, 2016 at 6:41 Baloon1985Baloon1985 892 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You can trigger it manually like:

$(document).ready(function () {
    $(window).on('hashchange', function () {
        //do something
    }).trigger('hashchange');
});

Or you can do it like:

$(document).ready(function () {
    //attaching the event listener
    $(window).on('hashchange', function () {
        //do something
    });

    //manually tiggering it if we have hash part in URL
    if (window.location.hash) {
        $(window).trigger('hashchange')
    }
});
发布评论

评论列表(0)

  1. 暂无评论