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?
Try this :
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