Reputation: 3823
i have this links:
<a id = "link_1" href = "#">Cars</a>
<a id = "link_2" href = "#">Colors</a>
<a id = "link_3" href = "#">Users</a>
<a id = "link_4" href = "#">News</a>
how to get the ID numbers on which I click? For examples i push on link Cars, and i wish get 1, push on Users, get number 3.
Thanks
Upvotes: 2
Views: 1156
Reputation:
$(function() {
$('a').click(function() {
var id = $(this).attr('id');
alert(id.match(/\d+/)[0];
});
});
Upvotes: 1
Reputation: 5836
$("a").click(function () {
var theIdNum = parseInt(this.id.replace(/\D/g, ''), 10);
});
honestly I don't know if that will even work.
Upvotes: 0
Reputation: 1052
besser use the html data attribute: data-id="1";
$(document).ready(function() {
$('#links').find('a').each(function() {
$(this).click(function() { alert($(this).attr('data-id')); return false; })
})
})
full code : http://jsbin.com/eyona4/
Upvotes: 0
Reputation: 1395
Apply a class to all of them to allow for easier manipulation.
This works as described:
<a id="link_1" class="get_id" href="#">Cars</a>
<a id="link_2" class="get_id" href="#">Colors</a>
<a id="link_3" class="get_id" href="#">Users</a>
<a id="link_4" class="get_id" href="#">News</a>
<script type="text/javascript">
jQuery(document).ready(function() {
$('.get_id').click(function () {
if ($(this).attr('id').match('^link_([0-9]+)$'))
{
id_num = RegExp.$1;
alert(id_num);
}
});
});
</script>
Upvotes: 0
Reputation: 13003
$("a").click(function(event) {
event.preventDefault();
var theid = $(this).attr("id").split("_");
theid = theid[1]; //here is the number
}
Upvotes: 1
Reputation: 17084
This will do:
$('a').click(function(){
alert(this.id.split("_")[1]);
});
Upvotes: 9