jQuery: запускать функцию, когда в URL есть определенный хэш ...? - PullRequest
1 голос
/ 29 сентября 2011

Я ищу, чтобы выполнить функцию, когда страница загружается с определенным хешем в URL.

Так что, если я зайду www.mypage.com/hello.html#functionplease, код будет выполнен.

Кто-нибудь может указать мне правильное направление?

Любой совет приветствуется!

Ответы [ 4 ]

9 голосов
/ 29 сентября 2011
var h = location.hash.substr(1);
if (h == 'functionplease')
    functionplease();

substr (1) удалить # в хэше.

Много функций?Нет проблем!

switch(location.hash.substr(1)) {
    case 'buy': buy(); break;
    case 'sell': sell(); break;
    case 'other': other(); break;
}
0 голосов
/ 30 сентября 2011

попробовать:

<script type="text/javascript">
    window.onload = function () {
        setInterval(pollHash, 100);
    }


    var lasthash = '';
    function pollHash() {
        if (window.location.hash == lasthash) { return; }

        lasthash = window.location.hash;
        console.log('hash is changed! Current hash is: ' + lasthash);

        switch (lasthash) {
            case '???' :
                /* do something */
                break;
            default:
                /* do nothing */
                break;
        }
    }

</script>

посмотрите на: http://ajaxpatterns.org/Unique_URLs#Unique_URL_Sum_Demo

0 голосов
/ 29 сентября 2011
var pathname = window.location.pathname; 
if(pathname.indexOf("#") != -1){
    //call your function
}
0 голосов
/ 29 сентября 2011

Должно работать следующее:

<script type="text/javascript">
    //check if hash tag exists in the URL
    if(window.location.hash)
    {
        //set the value as a variable, and remove the #
        var hash_value = window.location.hash.replace('#', '');

        //check value of hash
        if (hash_value == 'functionplease'){
           // execute code
        }  
    }
</script>

Надеюсь, это поможет!

...