简体   繁体   English

使用jQuery选择第一个元素

[英]Selecting first # of elements with jQuery

I have the following HTML: 我有以下HTML:

<input id="1" type="checkbox"/>
<label for="1">bla bla</label>
<br/>
<input id="2" type="checkbox"/>
<label for="2">hello hello</label>
<br/>
.
.
.
etc...

Is there a way to select first few inputs here in one call? 有没有办法在一个呼叫中选择前几个输入? In other words, I don't want to select them all and loop through each one. 换句话说,我不想全部选中它们并遍历每个。 Just 1 statement to select, for example, first 3. 仅需1条语句即可选择,例如前3条。

Simply select all and slice the result as you need, 只需全选并根据需要分割结果,

$('input').slice(0, 3) //will return first 3 input.

DEMO DEMO

你的意思是这样的?

var firstThree = $('#1, #2, #3')

这应该做到这一点

$("input:lt(3)")

The jQuery function slice lets you specify only a subset of the results: jQuery函数切片可让您仅指定结果的子集:

$('input').slice(0, 3)

Where 0 is the first index and 3 is the first index not included , so 2 is the last index and you get the three items. 其中0是第一个索引,3是不包括第一个索引 ,因此2是最后一个索引,您将获得三个项目。

Here you go: 干得好:

   $('input').filter(function(index) {
       return index < 3;        
    });

You can change the 3 to be however many items you want. 您可以将3更改为任意数量。

You can use the jQuery :gt and :lt selectors: 您可以使用jQuery :gt:lt选择器:

$('input:lt(3)').css('blah, 'blah');

This should select the first three input tags on the page. 这应该选择页面上的前三个输入标签。

You can use the :lt selector. 您可以使用:lt选择器。

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

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

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