2010-10-07 7 views
2

Recherche de la valeur d'attribut à partir d'un hachage d'URL.jQuery find attribut from url hash

// URL 
http://url.com/index.html#link 

// HTML 
<a href="#link" rel="3">Some link</a> 

// JS 
var anchor = window.location.hash.substring(1); 
// Need help finding attribute value from finding the anchor 
var attribute = .find('#+anchor').attr('rel'); //this needs to have a value of 3 

Toute aide appréciée. Merci :)

Répondre

6

Vous pouvez le faire en utilisant un attribute-equals selector, comme ceci:

$('a[href="'+window.location.hash+'"]').attr("rel") 

Ou .filter(), comme ceci:

$("a").filter(function() { return this.hash == location.hash; }).attr("rel") 

Le .hash commençant par # sera compatible, donc pas besoin pour supprimer/ajouter ceci, il suffit de l'utiliser tel quel.

+0

grand. maintenant, comment puis-je obtenir l'inverse ... trouver un #hash d'un rel? – Jeffrey

+0

@Jeffrey - Le même type de sélecteur, par exemple: '$ ('a [rel =" quelque chose "]'). Attr (" href ")' –

+0

merci, ça l'a fait – Jeffrey

0

Est-ce ce que vous cherchez?

var attribute = $("a[href='#" + anchor + "']").attr('rel'); 
1
$('a[href=' + window.location.hash +']').attr("rel"); 
+1

L'espace supplémentaire rendra cela inopérant , vous avez un sélecteur descendant supplémentaire là-bas. –

+0

Votre droite, iPad autocorrect – jps