如何用jquery選擇前N個元素?

[英]How to select first N elements with jquery?


<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.

我想只在事件上添加onmouse到前三個li(tab1,tab2,tab3)。如何寫if條件。

6 个解决方案

#1


40  

You don't need an if - you can use the jQuery :lt() selector

你不需要if - 你可以使用jQuery:lt()選擇器

$('ul li:lt(3)').mouseenter(function(){});

Note that the index is zero-based, so the first three are 0, 1 and 2

請注意,索引從零開始,因此前三個是0,1和2

http://api.jquery.com/lt-selector/

#2


5  

Actually, you don't need any conditional statement, you can do it with a single selector:

實際上,您不需要任何條件語句,您可以使用單個選擇器執行此操作:

$('ul li:first').mouseenter(function() {
});

If you want to further "filter" your <li> nodes, be more specific, like

如果你想進一步“過濾”你的

  • 節點,那就更具體了

  • $('ul li.navahead:first').mouseenter(function() {
    });
    

    update:

    To answer your updated question:

    要回答您更新的問題:

    $('ul li[class^=tab]').mouseenter(function() {
    });
    

    ^= will select all classnames which begin with a given string ("tab" in this case)

    ^ =將選擇以給定字符串開頭的所有類名(在本例中為“tab”)

    #3


    2  

    You don't need "if". Use selectors

    你不需要“如果”。使用選擇器

    $("ul li:first")
    

    #4


    0  

    $("li.tab1, li.tab2, li.tab3").mouseover(function(){
        // write your code here
    });
    

    #5


    0  

    I guess it should be like:

    我想應該是這樣的:

     $(".tab1").mouseover(function() {
    
    });
    

    #6


    0  

    You can use :nth-child(-n+{TARGET_NUMBER})

    您可以使用:nth-​​child(-n + {TARGET_NUMBER})

    Use ul li:nth-child(-n+3) to select first 3 elements.

    使用ul li:nth-​​child(-n + 3)選擇前3個元素。

    E.g.

    $('ul li:nth-child(-n+3)').mouseenter(function() {
        // your code goes here
    });
    

    注意!

    本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/07/18/720fe485a9eb6edd4b3470b2c62c22a3.html



     
    粤ICP备14056181号  © 2014-2021 ITdaan.com