最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterate through elements, adding click event to each of them - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

This 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.

发布评论

评论列表(0)

  1. 暂无评论