Javascript 使用jQuery选择具有特定类的第一个和最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4082600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:31:18  来源:igfitidea点击:

Select first and last element with particular class using jQuery

javascriptjqueryhtml

提问by tsusanka

I have a list of spans with particular class "place" and some of them have class "activated". Is there a way to select the first item with class "activated" and the last?

我有一个具有特定类“位置”的跨度列表,其中一些具有“激活”类。有没有办法选择“已激活”类的第一个项目和最后一个项目?

<span class="place" onclick="activate();">1</span>
<span class="place" onclick="activate();">2</span>
<span class="place activated" onclick="activate()">3</span>
<span class="place activated" onclick="activate();">4</span>
<span class="place activated" onclick="activate();">5</span>
<span class="place activated" onclick="activate();">6</span>
<span class="place" onclick="activate();">7</span>

回答by Stephen

var firstspan = $('span.activated:first'),
    lastspan = $('span.activated:last');

By the way, if you're using jQuery, what's with all the inline click events?

顺便说一句,如果您使用的是 jQuery,那么所有内联点击事件有什么用?

You could add some code like so:

你可以像这样添加一些代码:

$('span.place').click(function() {
    activate(); // you can add `this` as a parameter
                // to activate if you need scope.
});

回答by Jordan Running

var places = $('span.place.activated');

var first = places.first(),
    last  = places.last();

Explanation: The span.places.activatedselector will get all <span>s with both "place" and "activated" classes. Then the first()and last()methods will return the first and last items of that set. This is preferable to using the :firstand :lastpseudoselectors because selection is expensive and this way we only do selection once and then rely on (cheap) array operations to get the first and last elements.

说明:span.places.activated选择器将获得所有<span>具有“位置”和“激活”类的 s。然后first()andlast()方法将返回该集合的第一个和最后一个项目。这比使用:first:last伪选择器更可取,因为选择很昂贵,这样我们只进行一次选择,然后依靠(便宜的)数组操作来获取第一个和最后一个元素。

回答by Vasyl

If you take care about performance, than better use $('span.place.activated')instead $('.activated:first'). But, in this case, the second variant correct too.

如果你需要关心性能,优于使用$('span.place.activated')代替 $('.activated:first')。但是,在这种情况下,第二个变体也正确。

回答by Aaron Hathaway

var first = $('.activated:first');
var last = $('.activated:last');