Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call jquery function within "a" tag "onclick"

Tags:

jquery

here is my code:

<a href='P001' class='basic'>Read More</a><br>
<a href='P002' class='basic'>Read More</a><br>
<a href='P003' class='basic'>Read More</a><br>

my script:

$('.basic').click(function(id){
   $.ajax({
       url: 'display_pro.php?id='+$('.basic').attr('href'),
       success: function(data) {alert(data);}
   });
});

when i click all links it's always get the 'P001'. what is the problem? Thanks for your help.

like image 600
measmony Avatar asked Aug 14 '26 12:08

measmony


2 Answers

$('.basic').click(function(e) {
   var link = this; // <-- best practice
   $.ajax({
       url: 'display_pro.php?id=' + link.href, // use link here...
       success: function(data) {alert(data);}
   });
   return false; // <-- needed, prevents page from jumping into another page..
});
like image 188
Reigel Avatar answered Aug 17 '26 01:08

Reigel


Instead of +$('.basic').attr('href') you should do:

$(this).attr('href')

Otherwise, you are asking again for the set of items with the class as "basic" and grabbing the value of the first one. $(this) (or e.target) ensure you are getting the currently clicked item. Also, FYI, the argument passed to the function is not id--it is an event object.

like image 38
Brett Zamir Avatar answered Aug 17 '26 02:08

Brett Zamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!