Trigger click on URL with hashtag

走远了吗. 提交于 2019-12-08 01:36:33

问题


Can you trigger click on URL with hashtag?

For example:

I have this link: <a class="contact">Contact Me</a>

and when I visit www.example.com/#contact to fire: $('a.contact').trigger('click');

Is this possible by any hacky way?


回答1:


var hash = window.location.hash.slice(1); // get the hash, and strip out the "#"

if( hash /* && hash === 'contact' */ )  // if there was a hash
    $('a.' + hash ).trigger('click');   //    concatenate it into the selector



回答2:


You should be able to capture the hashchange event using the jQuery BBQ plugin (see last example on this page). Something along these lines should work:

$(window).bind("hashchange", function(e) {
    if ($.param.fragment() === 'contact') {
        $('a.contact').trigger('click');
    }
});

$(window).trigger("hashchange");

This should not only work when you first load the page, but also when something else changes the fragment.



来源:https://stackoverflow.com/questions/8887209/trigger-click-on-url-with-hashtag

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