tags:

views:

63

answers:

6

Hi,

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

+9  A: 

This will do:

$('a').click(function(){
  alert(this.id.split("_")[1]);
});
Gert G
Thanks, but I allways get: "undefined"
lolalola
@lolalola - Here's an example of Gert's answer using your HTML. http://jsfiddle.net/QpyVY/ Did you change something in your code from your question?
patrick dw
Now, i understand. I must id put in a tag, not on <div>. Thanks ;)
lolalola
@lolalola - Yes, inside of a jQuery event handler, `this` will refer to the element to which the handler was attached (specifically, the one that received the event). You can place the ID on a `<div>` if you'd like, but you'll just need to adjust your code as needed. :o)
patrick dw
@patrick dw - Thanks for making the jsfiddle example.
Gert G
@Gert - Not a problem. :o)
patrick dw
+1  A: 
$("a").click(function(event) {
    event.preventDefault();
    var theid = $(this).attr("id").split("_");
    theid = theid[1]; //here is the number
}
Davide Gualano
A: 

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>
vassilis
A: 

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/

ipsum
A: 
$("a").click(function () {
    var theIdNum = parseInt(this.id.replace(/\D/g, ''), 10);
});

honestly I don't know if that will even work.

SSpoke
A: 
$(function() {
  $('a').click(function() {
     var id = $(this).attr('id');
     alert(id.match(/\d+/)[0];
  });
});
Ninja Dude