admin管理员组

文章数量:1335596

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?

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?

Share Improve this question edited Feb 1, 2012 at 15:04 fivedigit 18.7k6 gold badges58 silver badges61 bronze badges asked Jan 31, 2012 at 16:43 gurehbguigurehbgui 14.7k33 gold badges111 silver badges190 bronze badges 2
  • 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 stackoverflow./questions/451785/… – Fabrizio Calderan Commented Jan 31, 2012 at 16:47
  • correct link : stackoverflow./questions/3545341/… – Fabrizio Calderan Commented Jan 31, 2012 at 16:53
Add a ment  | 

3 Answers 3

Reset to default 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/VKpRY/

jQuery 1.6 and earlier

$('li.nav a').click(function (e) {
  e.preventDefault();
  var id = $(this).parent().attr('id');
  ...
});
$("a").on('click',function (ee) {
ee.preventDefault();
alert($(this).parents("li:first").attr("id"));

})

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

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

Hope this helps,

Pete

本文标签: javascriptHow to get the ID of a selected ltligt or ltagt with jQueryStack Overflow