2012-10-31 39 views
1

我的基本jQuery的给定索引搜索元素或更高版本

<div class="letter">A</div> 
<div class="letter">B</div> 
<div class="letter"></div> 
<div class="letter">D</div> 
<div class="letter"></div> 

HTML和正在返回第一个空div的指数jQuery的功能(与类“字母”)

var firstEmptyIndex; 

var findStart = function(){ 
    var firstEmptyElement = $('div.letter:empty:eq(0)'); 
    firstEmptyIndex = firstEmptyElement.index('div.letter'); 
} 

如何扩展此findStart函数以传递变量,该变量将开始在给定索引处搜索空元素。例如,我想运行findStart(3),它将返回HTML示例(4)中第五个元素的索引。运行findStart(0)或findStart(1)将返回2.

+3

http://api.jquery.com/gt-selector/ – PeeHaa

+0

PeeHaa的回答正是你所需要的。我删除了我的回答 –

回答

3

您可以使用:gt:first组合:

var findStart = function(i){ 
    return $('div.letter:gt(' + i + '):empty:first').index('div.letter'); 
} 
+0

我认为你应该'返回$('div.letter:gt('+ i +'):empty:first')。index('div.letter');' –

+0

@ raina77ow我专注于在选择器上并没有注意到这一点。根据维加的建议改变。 – bfavaretto

+0

谢谢@Vega,你是对的。编辑。 – bfavaretto

0

您可以使用jQuery的filter方法,其中,在一种形式,可以让你通过一个过滤函数,它在你的索引。因此,下面应该工作:

someResultSet.filter(function (i) { return i < someOtherIndex; }) 
0

使用jQuery的过滤方法,没有文字只返回元素。

var selector = ".letter" ; 
$(selector).filter(function(){return !$(this).text()}).get(0) ; 
0

试试这一个,将工作
返回null没有空的元素被发现。
其他明智它会返回一个空元素索引

​​