How to execute a js function based on url hash url#nameoffunction

后端 未结 5 1361
执念已碎
执念已碎 2021-01-02 09:08

I saw some of websites executes a JavaScript function based on has in the URL. For example,

when I access http://domain.com/jobs#test

then the website execut

5条回答
  •  臣服心动
    2021-01-02 09:39

    Live Demo

    $(window).bind('hashchange', function() {
        var hash = document.location.hash;
        var func = hash.replace('#', '');
        eval(func + '()');
    });
    
    function asdf() {
        alert('asdf function');
    }
    
    function qwerty() {
        alert('qwerty function');
    }
    

    Note: eval() is dangerous. You should make a predefined array of safe functions, and call those.

提交回复
热议问题