Reputation: 17373
I've number of html href as shown below:
<a id="link1" href="http://www.google.com">USA </a>
<a id="link2" href="http://www.google.com.au">AU </a>
<a id="link2" href="http://www.google.com.nz">NZ </a>
I've jquery as below:
<script>
$("a").click(function () {
var link = $('a').attr('href');
alert(link);
dosomethingforlink(link);
});
</script>
Basically, with one click function above I would like to get the href value of <a>
tag (which is clicked) and do something different for each link.
Or do I need to create (#id).click
function for each Ids?
Could someone please help me if the above is possible using Jquery?
Upvotes: 0
Views: 3324
Reputation: 33618
Something like this may be
<script>
$("a").click(function (event) {
event.preventDefault();
var link = $(this).attr('href');
alert(link);
dosomethingforlink(link);
});
</script>
Adds:
use event.preventDefault() from navigation to the url in anchor tag
Upvotes: 1
Reputation: 318172
ID's should be unique, so do not use the same ID on more than one element.
Something like this maybe:
$("a[id^='link']").on('click', function (e){
e.preventDefault();
switch ($(this).attr('href')) {
case 'http://www.google.com' :
//do something
break;
case 'http://www.google.com.au' :
//do something
break;
default:
//do something else
....etc
}
});
Upvotes: 0
Reputation: 38147
Try this :
$("a").click(function () {
var link = $(this).attr('href');
alert(link);
dosomethingforlink(link);
});
I have changed $('a')
to $(this)
as $('a')
will get all of the anchors .. $(this)
will only get the currently clicked one.
Here is a quick working demo .. you will see the last line is event.preventDefault()
- it prevents the default action (ie following the href) from happening and allowing your function to execute. event.preventDefault()
docs here
Upvotes: 4
Reputation: 123367
$("a").click(function (evt) {
evt.preventDefault();
var link = $(this).attr('href');
alert(link);
dosomethingforlink(link);
});
you should use preventDefault()
otherwise you won't be able to execute further code (your link gets clicked and the page is immediately changed)
Upvotes: 1