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
3 Answers
Reset to default 7Try 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