Exemple:
www.site.com/index.php#hello
En utilisant jQuery, je veux mettre la valeur hellodans une variable:
var type = …
Exemple:
www.site.com/index.php#hello
En utilisant jQuery, je veux mettre la valeur hellodans une variable:
var type = …
Réponses:
Pas besoin de jQuery
var type = window.location.hash.substr(1);
.slice(1)au lieu de .substr(1)cela devrait offrir une augmentation modeste des performances, même si cela ne fait aucune différence dans la vie réelle.
Vous pouvez le faire en utilisant le code suivant:
var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);
var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
hash = type[1];
alert(hash);
Démo de travail sur jsfiddle
ifdéclaration peut être raccourcie var hash = type[1] || "";.
Utilisez le code JavaScript suivant pour obtenir la valeur après le hachage (#) à partir d'une URL. Vous n'avez pas besoin d'utiliser jQuery pour cela.
var hash = location.hash.substr(1);
J'ai ce code et ce tutoriel d'ici - Comment obtenir la valeur de hachage à partir d'une URL en utilisant JavaScript
J'ai eu l'URL de l'exécution, ci-dessous a donné la bonne réponse:
let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);
J'espère que cela t'aides
Basé sur le code d'AK, voici une fonction d'assistance. JS Fiddle Here ( http://jsfiddle.net/M5vsL/1/ ) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);