迭代元素,向每个元素添加click事件

Jos*_*eau 2 javascript each jquery click

jQuery新手在这里.

如果我有这个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>
Run Code Online (Sandbox Code Playgroud)

我想为click每个li项目添加一个事件,这样我就可以获得我id所在的元素.现在我只是对我正在使用的索引发出警报(并且它也没有工作),但我真的想要我所在项目的ID,而不是我的选择器返回的数组的索引.

这是我试过了,但它似乎没有工作,我想我可能有错误的理解each()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
  });
Run Code Online (Sandbox Code Playgroud)

Emi*_*l H 7

这应该工作:

$('#floor-selector li').on('click', function() {
    alert('I am the '+$(this).attr('id')+' element');
});
Run Code Online (Sandbox Code Playgroud)

在幕后,jQuery做了很多魔术,并且基本上绑定了传递给元素的函数.this因此引用您单击的元素并将其传递给jQuery函数:$(this)返回包含在jQuery对象中的元素.当然你可以直接访问idon this.