Jak można sprawdzić #hash w adresie URL za pomocą JavaScript?

Mam kod JavaScript jQuery, który chcę uruchomić tylko wtedy, gdy w adresie URL znajduje się link zakotwiczający hash ( # ). Jak można sprawdzić dla tego znaku za pomocą JavaScript? Potrzebuję prostego testu catch-all, który wykrywałby adresy URL takie jak te:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

W zasadzie coś w stylu:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}
Gdyby ktoś mógł wskazać mi właściwy kierunek, byłoby to bardzo mile widziane.
Author: Danil Speransky, 2008-11-18

18 answers

Proste:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
 1223
Author: Gareth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-30 01:52:30
  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }
 278
Author: Mark Notton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-01 13:07:28

Wpisz:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>
 46
Author: José Leal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-06 15:35:28

Jeśli URI nie jest lokalizacją dokumentu, ten fragment zrobi to, co chcesz.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}
 26
Author: Marc Diethelm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-08 10:42:21

Próbowałeś tego?

if (url.indexOf("#") != -1)
{
}

(Gdzie url jest URL, który chcesz sprawdzić, oczywiście.)

 18
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-11-18 11:37:01
$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

To rozwiąże problem;)

 15
Author: Oral ÜNAL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-31 13:44:31
window.location.hash 

Zwróci identyfikator hash

 12
Author: user2327502,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-27 18:31:45

...albo jest selektor jquery:

$('a[href^="#"]')
 10
Author: BaronVonKaneHoffen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-19 13:18:42

Oto, co możesz zrobić, aby okresowo sprawdzać zmianę skrótu, a następnie wywoływać funkcję przetwarzającą wartość skrótu.

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}
 6
Author: Emmanuel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-05 22:23:38

Większość ludzi zna właściwości adresu URL w dokumencie.miejsce. To świetnie, jeśli interesuje Cię tylko bieżąca strona. Ale pytanie dotyczyło możliwości analizowania anchorów na stronie, a nie samej strony.

Większość ludzi zdaje się tęsknić za tym, że te same właściwości URL są również dostępne dla elementów anchor:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});
 5
Author: Nicholas Davison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-05 17:32:24

Kuropatwa i Gareth komentarze powyżej są świetne. Zasługują na osobną odpowiedź. Najwyraźniej właściwości hash i search są dostępne na dowolnym obiekcie łącza html:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Lub

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Jeśli potrzebujesz tego na zwykłej zmiennej string i zdarzy ci się mieć jQuery wokół, powinno działać:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(ale to może trochę przesadzone .. )

 3
Author: commonpike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-08 04:08:28
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
 3
Author: Graham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-06 10:57:00

Wrzucenie tego tutaj jako metody abstrakcji właściwości lokalizacji z arbitralnych łańcuchów podobnych do URI. Chociaż {[1] } jest prawdą, każda próba wywołania Location powie Ci, że jest to nielegalny konstruktor. Można jeszcze dostać się do rzeczy takich jak hash, query, protocol itd, ustawiając łańcuch jako właściwość href elementu kotwicy DOM, który następnie będzie współdzielił wszystkie właściwości adresu z window.location.

Najprostszym sposobem na to jest:

var a = document.createElement('a');
a.href = string;

string.hash;

Dla wygody, napisałem trochę biblioteka, która używa tego do zastąpienia natywnego konstruktora Location takim, który będzie pobierał łańcuchy znaków i produkował obiekty podobne do window.location: Location.js

 3
Author: Barney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-10 13:58:13
function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}
 3
Author: user2465270,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-23 09:27:20

Zwykle klikamy najpierw niż zmieniamy lokalizację, więc po kliknięciu jest dobrym pomysłem, aby setTimeOut aby uzyskać zaktualizowane okno.miejsce.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

Lub możesz posłuchać lokalizacji za pomocą:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

Napisałem jQuery plugin który robi coś takiego co chcesz zrobić.

To prosty Router anchor.
 1
Author: Rolando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-21 14:18:39

Oto prosta funkcja, która zwraca true lub false (has / doesn ' t have a hashtag):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

Zwraca true w tym przypadku.

Na podstawie komentarza @ jon-skeet.

 0
Author: dnns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-29 11:22:07

Jest to prosty sposób na przetestowanie tego dla bieżącego adresu URL strony:

  function checkHash(){
      return (location.hash ? true : false);
  }
 0
Author: aabiro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-18 09:31:01

Czasami dostajesz pełny ciąg zapytania, taki jak " #anchorlink?firstname=mark "

To jest mój skrypt, aby uzyskać wartość hash:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink
 -3
Author: markg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-27 08:45:24