2011-10-08 7 views
6

Sto studiando Google Ajax Crawlable

Io uso $(window) bind hashchange per controllare il caricamento della pagina Ajax.

mio url del tipo:

ci deve due tipo di cambiamento

  1. domain.com/#!/apple&num=1 =>domain.com/#!/apple&num=2

  2. domain.com/#!/apple&num=1 =>domain.com/#!/banana&num=1

così come verificare se $(window) bind hashchange ha cambiato la parte hash da apple =>banana? Grazie.

$(window).bind('hashchange', function() { 
    // make a judge like if(){}else{} 
}); 
+0

Il secondo hash aggiornato non ha cambiato solo il nome della frutta, ma anche il numero. –

risposta

13

Memorizzare l'hash in una variabile e aggiornare la variabile alla fine della funzione. Prendere in considerazione:

(function(){ 
    var lastHash = location.hash; 
    $(window).bind('hashchange', function() { 
     var newHash = location.hash; 
     // Do something 
     var diff = compareHash(newHash, lastHash); 
     alert("Difference between old and new hash:\n"+diff[0]+"\n\n"+dif[1]); 

     //At the end of the func: 
     lastHash = newHash; 
    }); 

    function compareHash(current, previous){ 
     for(var i=0, len=Math.min(current.length, previous.length); i<len; i++){ 
      if(current.charAt(0) != previous.charAt(0)) break; 
     } 
     current = current.substr(i); 
     previous = previous.substr(i); 
     for(var i=0, len=Math.min(current.length, previous.length); i<len; i++){ 
      if(current.substr(-1) != previous.substr(-1)) break; 
     } 

     //Array: Current = New hash, previous = old hash 
     return [current, previous]; 
    } 
})() 
+0

che bel lavoro. Grazie. – Giberno

3

Vorrei memorizzare l'hash originale in una variabile, quindi esaminare il nuovo hash per giudicare la modifica. Una volta fatto, imposta il nuovo hash come originale:

var originalHash = window.location.hash; 
$(window).bind('hashchange', function() { 
    var newHash = window.location.hash; 
    //do your stuff based on the comparison of newHash to originalHash 

    originalHash = newHash; 
}); 
+1

posso rilevare il cambiamento di (window.location) e gestirlo? (senza jquery) – BergP

Problemi correlati