Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i extract text after hash # in the href part from a tag?

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 tab1 if Any tab1 Label is clicked, tab2 if tab2 Label is clicked and so on...

like image 603
KoolKabin Avatar asked Oct 05 '10 05:10

KoolKabin


4 Answers

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

$('a').click(tellMyName);
like image 58
sje397 Avatar answered Oct 31 '22 15:10

sje397


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.

like image 24
rob waminal Avatar answered Oct 31 '22 14:10

rob waminal


You can do something like this

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

Check it out.

like image 6
alex Avatar answered Oct 31 '22 14:10

alex


function tellMyName() {
  alert(this.hash.replace('#',''));
}

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

crazy fiddle

like image 2
Reigel Avatar answered Oct 31 '22 15:10

Reigel