遍历元素,向每个元素添加click事件

Iterate through elements, adding click event to each of them

本文关键字:元素 添加 click 事件 遍历      更新时间:2023-09-26

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>

我想为每个li项添加一个click事件,这样我就可以获得我所在元素的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
  });

这应该有效:

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

在幕后,jQuery做了一堆魔术,基本上将传递给元素的函数绑定在一起。因此,this引用您正在单击的元素,并将其传递给jQuery函数:$(this)将返回封装在jQuery对象中的元素。当然,您可以直接访问this上的id