Javascript 仅针对具有相同类名的一个元素触发单击事件

Javascript 仅针对具有相同类名的一个元素触发单击事件,javascript,jquery,html,Javascript,Jquery,Html,我有多个具有相同类名的div:ag列表项 <!-- item one --> <div class="ag-list-item"> </div> <!-- item two --> <div class="ag-list-item"> </div> <!-- item three --> <div class="ag-list-item"> </div> 正如承诺的那样,我已经更新了

我有多个具有相同类名的div:
ag列表项

<!-- item one -->
<div class="ag-list-item">
</div>

<!-- item two -->
<div class="ag-list-item">
</div>

<!-- item three -->
<div class="ag-list-item">
</div>

正如承诺的那样,我已经更新了我的帖子

$(document).ready(function () {

    // If you want to select the first element :
    $('.ag-list-item:first span span').click(function () {
        // Your code
    });

    // If you want to select the second element, in this example
    // Don't forget the quotes around the desired number
    $('.ag-list-item:eq("1") span span').click(function () {
        // Your code
    });

    // If you want the last element :
    $('.ag-list-item:last span span').click(function () {
        // Your code
    });

)};

请查找与此示例相关的内容(我对一些设计风格有了更好的理解)

如果您想要一个纯Javascript解决方案来提高速度,这可以做到:

var els = document.getElementsByClassName('ag-visible-icons');

els[0].addEventListener('click', function() {
  // Do something
});
对于jQuery,您可以尝试:

$('.ag-visible-icons').first().click(function() {
  // Do somehting
});

这是假设您在“.ag列表项:first span”路径中显示的类是ag可见图标类

,这正是我所需要的!谢谢点击带有ag类图标的span是否可见?@KrakenDev我假设的问题中没有指定,因为ag列表项span span最终会出现在icons类上,我的回答需要知道这是否是目标class@Kyle.BelangerKrankenDev的vanilla JS答案允许您使用一个特定的索引,vanilla JS示例将非常好,但它实际上并没有为me@Kyle.Belanger应该是的,你用的是Chrome吗?在发布之前,我在JSFIDLE中对其进行了测试,并在.ag可见图标范围内放置了一些文本,然后在单击时提醒该文本,它就工作了。现在,这只会提醒FOO(单击第一个范围)是的,这是我所想到的解决方案。但在我的小提琴测试中,我忘记了数字周围的简单引号:eq('1'),所以我没有发布它。无论如何,很高兴能帮上忙:)
$('.ag-visible-icons').first().click(function() {
  // Do somehting
});