jQuery newbie here.
If I have this html:
<ul id="floor-selector">
<li id="floor-1">Ground Floor</li>
<li id="floor-2">Second Floor</li>
<li id="floor-3">Third Floor</li>
<li id="floor-4">Premier Floor (Premier Floor)</li>
</ul>
I want to add a click
event to each li
item, such that I can get the id
of the element I am on. Right now I just have an alert with the index I'm on (and it's not working either), but I really want the ID of the item I'm on, not the index of the array returned by my selector.
Here's what I tried, but it doesn't seem to work, I think I might have the wrong understanding of each()
or click()
.
$('#floor-selector li').each( function(index, node) {
node.click( function(){ alert('I am on the '+index+'th element'); } );
// but I really want to get the ID of this element
});
jQuery newbie here.
If I have this html:
<ul id="floor-selector">
<li id="floor-1">Ground Floor</li>
<li id="floor-2">Second Floor</li>
<li id="floor-3">Third Floor</li>
<li id="floor-4">Premier Floor (Premier Floor)</li>
</ul>
I want to add a click
event to each li
item, such that I can get the id
of the element I am on. Right now I just have an alert with the index I'm on (and it's not working either), but I really want the ID of the item I'm on, not the index of the array returned by my selector.
Here's what I tried, but it doesn't seem to work, I think I might have the wrong understanding of each()
or click()
.
$('#floor-selector li').each( function(index, node) {
node.click( function(){ alert('I am on the '+index+'th element'); } );
// but I really want to get the ID of this element
});
Share
Improve this question
edited Aug 24, 2013 at 18:46
Andy G
19.4k5 gold badges49 silver badges70 bronze badges
asked Aug 24, 2013 at 18:44
Joshua SoileauJoshua Soileau
3,0259 gold badges44 silver badges52 bronze badges
1 Answer
Reset to default 7This should work:
$('#floor-selector li').on('click', function() {
alert('I am the '+$(this).attr('id')+' element');
});
Behind the scenes jQuery does a bunch of magic and essentially binds the function you pass to the element. this
therefore references the element that you are clicking and passing it to jQuery functio: $(this)
gives you back that element wrapped in a jQuery object. Of course you could simply access the id
on this
directly.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131091a4612977.html
评论列表(0条)