Reputation: 6927
I am remaking a page on the admin section of a website I administer so that it uses jQuery and AJAX. On one of the pages I have a list of items. Next to each item there is a link which is something like this:
<a href="delete.php?id=48" class="del_link">delete</a>
If I give these links a class I can easily apply a jQuery function to all of them but they would all call the same function in the same way. My question is: what is the best way for the function to get the item's id without including JavaScript inline with the html?
Update: Thanks for the pointers, everyone. I've ended up using this:
$(".del_link").click(function(){
var del_link = $(this).attr('href');
$("#results").load(del_link, function (){
$("#results").show().delay().fadeTo(2000, 0);
})
})
The php file that the ajax calls responds in different ways if it's been requested by ajax or normally - if it's ajax it outputs a response (e.g. "Item was deleted successfully") which can be displayed in the #results div. If someone has javascript disabled the client will be directed to the same php page but it will redirect them once the item is removed.
Upvotes: 1
Views: 218
Reputation: 187110
In HTML 5 you can use data attributes. Something like
<a href="delete.php?id=48" class="del_link" data-id='48'>delete</a>
and jQuery
$("a.del_link").each(function(){
var id = $(this).attr('data-id');
});
Read this article on HTML 5 data attributes
Upvotes: 2
Reputation: 22485
well, you can get the href easily enough:
var id = $('.del_link a').attr('href');
then just parse the id out.
Upvotes: 2
Reputation: 328850
When you add an onClick
handler then this
will be the link.
Examine the href
attribute (use this.href
) and parse the ID.
Upvotes: 0
Reputation: 29775
Quick and dirty:
$('.del_link').click(function(){
var id = $(this).attr('href').split('=')[1];
// Do something with the ID here
});
Be warned, this won't work if the link URL has more than one querystring parameter. In that scenario you'd have to do some slightly more complicated parsing of the attr('href')
value.
Upvotes: 7