2010-10-05 39 views
16

我有以下內容的標籤:如何在標籤的href部分中提取哈希後的文本?

<a href="#tab1">Any tab1 Label</a> 
<a href="#tab2">tab2 Label</a> 
<a href="#tab3">Any tab3 Label</a> 
<script> 
function tellMyName() 
{ 
    alert(this.href); 
} 

</script> 

現在我想的tellMyName功能綁定到所有的一個標籤,並得到TAB1如果任何tab1的標籤被點擊,TAB2如果TAB2標籤點擊等等...

+0

還有一件事我已經注意到..。我認爲你必須使用Any tab1 Label等等.... – PHP 2010-10-05 05:47:37

回答

30
function tellMyName() { 
    alert(this.hash.substr(1)); 
} 

$('a').click(tellMyName); 
+0

對不起,我得到這樣的本地主機/ XYZ的webaddress在它前面太.. – KoolKabin 2010-10-05 05:48:02

+1

如果要this.hash.substr(1) – KoolKabin 2010-10-05 06:02:12

+0

@KoolKabin - 編輯。助教。 – sje397 2010-10-05 06:11:46

0
<script> 
function tellMyName() 
{ 
    var text = this.href; 
    text = text.replace("#",""); 
    alert(text); 
} 

</script> 
+0

對不起,我得到例如http webaddress://本地主機/ XYZ /在它前面太.. – KoolKabin 2010-10-05 05:45:56

+0

如下建議,你要綁定此功能定位標記。即$('a')。click(tellMyName); – 2010-10-05 05:48:28

19
function tellMyName() { 
    var str = this.href.split("#")[1]; 
    alert(str); 
} 
只有

不是所有的時間散列部將鏈接上顯示。有時主機被添加到href。通過拆分與hash(#)的href和獲得分割字符串的第二部分,你會得到你想要的。

+0

燁其返回正確的,因爲我正在尋找...日Thnx進行結合一直致力於爲http://stackoverflow.com/questions/3861076/how-can-i-extract-text-after-hash-in-the-href-part-from-a -tag/3861095#3861095 – KoolKabin 2010-10-05 05:50:07

0

試試這個 -

<a href="#tab1">Any tab1 Label</a> 
<a href="#tab2">tab2 Label</a> 
<a href="#tab3">Any tab3 Label</a> 

<script type="text/javascript"> 
$('a').click(function(){ 
alert(this.hash.split('#')[1]); //This will alert # part in clicked anchor tag 
}); 
</script> 
2
function tellMyName() { 
    alert(this.hash.replace('#','')); 
} 

$('a').click(tellMyName); 

crazy fiddle

3

你可以做這樣的事情

var fragment = $('a#my-link')[0].hash.substr(1); 

Check it out.

0

您可以ü SE是這樣的:

... 
var activeTab = $(this).attr("href"); 
$(activeTab).fadeIn(); 
... 

此使用的href = 「#標籤-ID」 爲定位要#標籤-id元素,並且在褪色

0
function tellMyName() { 
    var str = this.prop("hash").substr(1) 
    alert(str); 
} 

this.prop("hash") will return the hash value i.e #tab1 
相關問題