Ottieni l'URL corrente in jQuery
Sundeep Dawadi
30 gennaio 2023
-
Attributo
href
per ottenere l’URL corrente in jQuery - Accedi alle proprietà specifiche dell’URL in jQuery
![Ottieni l'URL corrente in jQuery](/img/jQuery/feature-image---How-to-get-current-url-in-jQuery.webp)
Ci sono spesso casi in cui vuoi vedere dove si sta caricando il tuo codice jQuery. Per ogni finestra aperta nel browser, il browser dà accesso al suo oggetto window
. Come parte dell’oggetto window
, l’oggetto location
fornisce informazioni sull’URL corrente.
Attributo href
per ottenere l’URL corrente in jQuery
Per ottenere l’URL corrente, puoi accedere all’attributo href
dell’oggetto location
del browser.
<script>
var url = $(location).attr('href');
// Returns full URL
(https://example.com/path/example.html)
var pathname = $(location).attr('pathname');
// Returns path only (/path/example.html)
var origin = $(location).attr('origin');
// Returns base URL (https://example.com)
</script>
Nota: In modo vanilla JavaScript, è possibile accedervi tramite window.location.href
.
Accedi alle proprietà specifiche dell’URL in jQuery
L’oggetto location
viene fornito con proprietà aggiuntive dell’URL.
Proprietà | Descrizione |
---|---|
hash |
parte di ancoraggio (#) di un URL |
host |
nome host e numero di porta di un URL |
hostname |
nome host di un URL |
href |
intero URL |
origin |
protocollo, nome host e numero di porta di un URL |
pathname |
nome del percorso di un URL |
port |
numero di porta di un URL |
protocol |
protocollo di un URL |
search |
stringa di query parte di un URL |