2010-10-07 20 views
2

試圖從網址哈希中查找屬性值。jQuery從網址哈希中查找屬性

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

所有幫助表示讚賞。謝謝:)

回答

6

您可以使用attribute-equals selector做到這一點,就像這樣:

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

或者.filter(),像這樣:

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

.hash開始#將是一致的,所以沒必要刪除/添加它,只需按原樣使用它。

+0

很好。現在,我怎麼能得到相反的...從rel找到#hash? – Jeffrey 2010-10-07 21:32:39

+0

@Jeffrey - 相同類型的選擇器,例如:'$('a [rel =「something」]')。attr(「href」)' – 2010-10-07 21:33:40

+0

謝謝,這樣做 – Jeffrey 2010-10-07 21:49:08

0

這是你所需要的?

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

額外的空間將使這不起作用,你在那裏有一個額外的後代選擇器。 – 2010-10-07 21:01:22

+0

你的權利,iPad自動更正 – jps 2010-10-07 21:02:19