2010-10-05 36 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 
相关问题