Domanda

Ho del codice jQuery / JavaScript che voglio eseguire solo quando c'è un link di ancoraggio hash ( # ) in un URL. Come puoi verificare questo personaggio usando JavaScript? Ho bisogno di un semplice test generale che rilevi URL come questi:

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

Fondamentalmente qualcosa del genere:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

Se qualcuno potesse indicarmi la giusta direzione, sarebbe molto apprezzato.

È stato utile?

Soluzione

Semplice:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

Altri suggerimenti

  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
  }

Inserisci quanto segue:

<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>

Se l'URI non è l'ubicazione del documento, questo frammento farà ciò che desideri.

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

if (hash) {
    alert(hash)
} else {
    // do something else
}

Hai provato questo?

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

(Dove url è l'URL che si desidera controllare, ovviamente.)

$('#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!
});

Questo risolverà il problema;)

window.location.hash 

restituirà l'identificatore hash

... o c'è un selettore jquery:

$('a[href^="#"]')

Ecco cosa puoi fare per controllare periodicamente una modifica dell'hash, quindi chiamare una funzione per elaborare il valore dell'hash.

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);
}

Molte persone sono a conoscenza delle proprietà dell'URL in document.location. È fantastico se sei interessato solo alla pagina corrente. Ma la domanda riguardava la possibilità di analizzare le ancore su una pagina e non sulla pagina stessa.

Ciò che la maggior parte delle persone sembra perdere è che quelle stesse proprietà URL siano disponibili anche per ancorare elementi:

// 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
   }
});
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; 
  }
}

I commenti di Partridge e Gareths sopra sono fantastici. Meritano una risposta separata. Apparentemente, le proprietà di hash e ricerca sono disponibili su qualsiasi oggetto html Link:

<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>

o

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

Dovresti averne bisogno su una normale variabile stringa e avere jQuery in giro, questo dovrebbe funzionare:

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

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

(ma forse è un po 'esagerato ..)

var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

Inserendolo qui come metodo per astrarre le proprietà della posizione da stringhe arbitrarie simili a URI. Sebbene window.location instanceof Location sia vero, qualsiasi tentativo di invocare Location ti dirà che è un costruttore illegale. Puoi ancora arrivare a cose come hash , query , protocol ecc impostando la tua stringa come proprietà href di un elemento di ancoraggio DOM, che condividerà quindi tutte le proprietà dell'indirizzo con window.location .

Il modo più semplice per farlo è:

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

string.hash;

Per comodità, ho scritto una piccola libreria che lo utilizza per sostituire il costruttore nativo Location con uno che prenderà stringhe e produrrà oggetti simili a window.location : < a href = "https://gist.github.com/barneycarroll/5310151" rel = "nofollow"> Location.js

Di solito i clic vanno prima delle modifiche alla posizione, quindi dopo un clic è una buona idea impostareTimeOut per ottenere window.location.hash

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

oppure puoi ascoltare la posizione con:

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

Ho scritto un plugin jQuery che fa qualcosa di simile cosa vuoi fare.

È un semplice router di ancoraggio.

Ecco una semplice funzione che restituisce true o false (ha / non ha un 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
}

Restituisce true in questo caso.

Basato sul commento di @ jon-skeet.

Questo è un modo semplice per testarlo per l'URL della pagina corrente:

  function checkHash(){
      return (location.hash ? true : false);
  }

a volte ottieni la stringa di query completa come " #anchorlink? firstname = mark & ??quot;

questo è il mio script per ottenere il valore hash:

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

returns -> #anchorlink
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top