Javascript 如何从标签的href部分中的hash #之后提取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3861076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can i extract text after hash # in the href part from a tag?
提问by KoolKabin
I have following a tags:
我有以下标签:
<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>
Now i want to bind the tellMyName function to all the a tags and get tab1if Any tab1 Labelis clicked, tab2if tab2 Labelis clicked and so on...
现在我想的tellMyName功能绑定到所有的一个标签,并得到TAB1如果任何tab1的标签被点击,TAB2如果TAB2标签被点击等等...
回答by sje397
function tellMyName() {
alert(this.hash.substr(1));
}
$('a').click(tellMyName);
回答by rob waminal
function tellMyName() {
var str = this.href.split("#")[1];
alert(str);
}
Not all the time only the hash part will be displayed on the link. Sometimes the Host is added to the href
. By splitting the href with the hash
(#) and get the second part of the split string, you'll get what you want.
并非总是只有哈希部分会显示在链接上。有时主机被添加到href
. 通过用hash
(#)分割 href并获得分割字符串的第二部分,您将得到您想要的。
回答by alex
You can do something like this
你可以做这样的事情
var fragment = $('a#my-link')[0].hash.substr(1);
回答by Reigel
function tellMyName() {
alert(this.hash.replace('#',''));
}
$('a').click(tellMyName);
crazy fiddle
疯狂的小提琴
回答by Beena Shetty
function tellMyName() {
var str = this.prop("hash").substr(1)
alert(str);
}
this.prop("hash") will return the hash value i.e #tab1
回答by Rulo Kobashikawa
You can use something like this:
你可以使用这样的东西:
...
var activeTab = $(this).attr("href");
$(activeTab).fadeIn();
...
This use href="#tab-id" for locate #tab-id element you want, and fade in.
这使用 href="#tab-id" 来定位您想要的 #tab-id 元素,然后淡入。
回答by Chinmayee G
<script>
function tellMyName()
{
var text = this.href;
text = text.replace("#","");
alert(text);
}
</script>
回答by Alpesh
Try this -
尝试这个 -
<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>