2012-10-30 15 views
5

ho il seguente codice nella visualizzazione MVC3:window.location.hash torna hash tag di fronte al valore

$(document).ready(function() { 
    if (window.location.hash) { 
     var manager= new Manager(); 

     manager.doSomeStuff(window.location.hash); 
    } 
}); 

La cosa interessante è che quando non c'è hash tag nell'URL, o c'è solo un esempio tag hash:

http://localhost:1223/Index/AboutUs 

http://localhost:1223/Index/AboutUs# 

Quando il window.location.hash è vuota e la funzione non viene eseguita. Ma quando c'è un valore nel tag hash:

http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8 

Il valore nel window.location.hash è #categoryId=5&manufacturerId=8

si può spiegare a me perché il tag # è incluso nel valore e perché quando non c'è valore dopo il tag #, lo window.location.hash è vuoto.

+0

Sì, lo fa ??? – adeneo

risposta

9

Non c'è molto da spiegare. È il modo in cui funziona.

Read more here: http://www.w3schools.com/jsref/prop_loc_hash.asp

definizione e l'utilizzo

The hash property returns the anchor portion of a URL, including the hash sign (#). 
+0

Sì, ho visto la definizione, ma sembra in qualche modo strano che il segno di hash venga restituito con il valore. Questo è il motivo per cui ho fatto la domanda. Inoltre, quando si imposta il valore window.location.hash, non è necessario aggiungere il segno di hash alla stringa. –

8

Si può cambiare se si vuole semplicemente cambiando il nome hash:

//Your old hash name caught in a variable 
var nameHash = location.hash; 

//Your new hash name without "#" 
var newHashName = nameHash.replace("#",""); 
+0

Ciò potrebbe produrre risultati indesiderati se l'hash contiene un altro carattere '#'. – Bernard

1

You can repalce # ma in questo modo creerà conflitto e non funzionerà con javascript.

Here is window.location reference link.

Ecco diversi esempi di utilizzo:

$(document).ready(function() { 
    var urlHash = window.location.hash; 
    var sampleURL = '#categoryId=5&manufacturerId=8'; 

    if (urlHash.length > 1) { 
     //do stuff 
    }else{ 
     //if value is empty, do stuff 
    } 

    if (urlHash === sampleURL) { 
     commonResponse(); 
    } 

    $('a').click(function() { 
     var target = $(this).attr('href'); 

     if (target === sampleURL) { 
      commonResponse(); 
     }  
    }); 

    function commonResponse() { 
     //alert('ok'); 
    } 
}); 
7
var hash = window.location.hash.substring(1); 

Questo omette il primo carattere della stringa, che è l'hash tag.

Problemi correlati