简体   繁体   中英

How to get the ID of a selected <li> or <a> with jQuery?

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?

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');
  ...
});
$("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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM