1

I have a list like this:

<li class="nav" id="1"><a href="#detail">a</a></li>
<li class="nav" id="2"><a href="#detail">b</a></li>
<li class="nav" id="3"><a href="#detail">c</a></li>

Now I want to use jQuery to save the id (1,2 or 3) which was clicked. How to do this?

fivedigit
  • 18,464
  • 6
  • 54
  • 58
gurehbgui
  • 14,236
  • 32
  • 106
  • 178
  • omitting for a while that those ID are not valid, where do you want to "save" the id? have you an event handler already defined somewhere? have you already made a search? is this a duplicate of http://stackoverflow.com/questions/451785/how-can-i-get-the-id-of-clicked-element-using-jquery – Fabrizio Calderan Jan 31 '12 at 16:47
  • correct link : http://stackoverflow.com/questions/3545341/jquery-get-the-id-value-of-li-after-click-function – Fabrizio Calderan Jan 31 '12 at 16:53

3 Answers3

7

Try the following (jQuery 1.7 and above)

$('li.nav a').on('click', function (e) {
  e.preventDefault();
  var id = $(this).parent().attr('id');
  ...
});

Fiddle: http://jsfiddle.net/VKpRY/

jQuery 1.6 and earlier

$('li.nav a').click(function (e) {
  e.preventDefault();
  var id = $(this).parent().attr('id');
  ...
});
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0
$("a").on('click',function (ee) {
ee.preventDefault();
alert($(this).parents("li:first").attr("id"));

})
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

For each selected jQuery object, simply use .attr('id');. Example follows:

$('li.nav').each(function () {
    var id = $(this).attr('id');
});

Hope this helps,

Pete

pete
  • 24,141
  • 4
  • 37
  • 51