如何使用jquery选择前N个元素? [英] How to select first N elements with jquery?
问题描述
我只想将 onmouse over 事件添加到前三个 li(tab1,tab2,tab3).if条件怎么写.
你不需要 if
- 你可以使用 jQuery :lt()
选择器
$('ul li:lt(3)').mouseenter(function(){});
注意索引是从零开始的,所以前三个是0、1和2
http://api.jquery.com/lt-selector/>
2020 年 7 月更新:
从 jQuery 3.4 开始,不推荐使用 :lt
伪类.从您的选择器中删除它,然后使用 .slice()
过滤结果.例如,:lt(3)
可以替换为对 .slice(0,3)
<div class="nav-top">
<ul>
<li class="tab1"><a href="/">test</a></li>
<li class="tab2"><a href="#">test</a></li>
<li class="tab3"><a href="#">test</a></li>
<li class="navahead"><a href="#">test</a></li>
<li class="navahead"><a href="#">test</a></li>
<li class="new"><a href="#">test</a></li>
</ul>
</div>
i want to only add onmouse over event to the first three li(tab1,tab2,tab3). how to write the if condition.
You don't need an if
- you can use the jQuery :lt()
selector
$('ul li:lt(3)').mouseenter(function(){});
Note that the index is zero-based, so the first three are 0, 1 and 2
http://api.jquery.com/lt-selector/
Update July 2020:
As of jQuery 3.4, the :lt
pseudo-class is deprecated. Remove it from your selectors and filter the results later using .slice()
. For example, :lt(3)
can be replaced with a call to .slice(0,3)
这篇关于如何使用jquery选择前N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!