简体   繁体   English

select 指定的第二个元素 class 使用 jQuery

[英]select second element of a specified class using jQuery

I have two elements with class of monkey on the page, and I want to attach one of them to a on click event listener.我在页面上有两个带有monkey class 的元素,我想将其中之一附加到单击事件侦听器。 they maybe siblings or completely independent elements.他们可能是兄弟姐妹或完全独立的元素。 Now I want to select the second element (which comes after the first one in html code)...现在我想要 select 第二个元素(在 html 代码中的第一个元素之后)...

This will select both of them and the event listener fires twice:这将 select 和事件侦听器触发两次:

const monkey = $(".monkey");

I used a lot of things with no luck to select the second element:我用了很多没有运气的东西来 select 第二个元素:

$(".monkey").get(1); 
$(".monkey")[1] 

Edit:编辑:

Here is the relation of two monkey elements one at the top and at the bottom of the image:这是图像顶部和底部两个猴子元素的关系:

在此处输入图像描述

You can use jQuery.eq as a function or as a selector.您可以将jQuery.eq用作 function 或选择器。

You can make use of a ternary operator to check whether the number of selected monkey elements is greater than 1, and if so, set monkey to the second element.可以使用三元运算符检查选中的monkey元素的个数是否大于1,如果是,则将monkey设置为第二个元素。 Otherwise, don't modify monkey .否则,不要修改monkey

 var monkey = $(".monkey"); //same as $(".monkey:eq(1)") monkey = monkey.length > 1? monkey.eq(1): monkey; monkey.on('click', function(){ console.log('click'); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="monkey">first element</div> <div class="monkey">second element</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM