我试图从给定索引处的元素开始遍历同一个父 div 的第一个孩子。
我有围绕“字母”div 的“单词”div。
HTML:
<div class="row">
<div class="twelve columns">
<div class="word">
<div class="character">
<div class="number">
4
</div>
<div class="options">
GHI
</div>
<div class="letter">H</div>
</div>
<div class="character">
<div class="number">
3
</div>
<div class="options">
DEF
</div>
<div class="letter">E</div>
</div>
<div class="character">
<div class="number">
5
</div>
<div class="options">
JKL
</div>
<div class="letter">L</div>
</div>
<div class="character">
<div class="number">
5
</div>
<div class="options">
JKL
</div>
<div class="letter">L</div>
</div>
<div class="character">
<div class="number">
6
</div>
<div class="options">
MNO
</div>
<div class="letter">O</div>
</div>
</div>
<div class="word">
<div class="character">
<div class="number">
4
</div>
<div class="options">
GHI
</div>
<div class="letter">I</div>
</div>
<div class="character">
<div class="number">
7
</div>
<div class="options">
PQRS
</div>
<div class="letter">S</div>
</div>
</div>
<div class="character">
<div class="number">
4
</div>
<div class="options">
GHI
</div>
<div class="letter"></div>
<div class="select">
<select class="word-options">
<option value="">Select a word</option>
<option value="IT">IT</option>
</select>
</div>
</div>
<div class="character">
<div class="number">
8
</div>
<div class="options">
TUV
</div>
<div class="letter"></div>
</div>
<div class="character">
<div class="number">
7
</div>
<div class="options">
PQRS
</div>
<div class="letter"></div>
</div>
<div class="character">
<div class="number">
3
</div>
<div class="options">
DEF
</div>
<div class="letter"></div>
</div>
<div class="character">
<div class="number">
2
</div>
<div class="options">
ABC
</div>
<div class="letter"></div>
</div>
</div>
</div>
jQuery:
var decoder = {};
decoder.firstEmptyIndexPrevious;
var findPrevStart = function(startIndex){
//if startIndex is not defined, set it to index of current cursor position
if (!startIndex){
startIndex = $('div.select').parents('div.character').first().index('div.character');
}
//index of first letter in word before the position of the start index. should return 5 in this example
decoder.firstEmptyIndexPrevious = $('div.character:lt(' + startIndex + ')').last().siblings('div.word div.character').first().index();
//decoder.firstEmptyIndexPrevious = $('div.character:lt(' + startIndex + ')').last().parent().children().first().index();
console.log('startIndex = ' + startIndex);
console.log('decoder.firstEmptyIndexPrevious = ' + decoder.firstEmptyIndexPrevious);
}
$(document).ready(function() {
findPrevStart();
});
基本上,在decoder.firstEmptyIndexPrevious 中,我想在该选择元素出现之前获取单词的第一个字母的索引(它将像光标一样动态地在DOM 中移动)。startIndex 按预期返回 7,但 decoder.firstEmptyIndexPrevious 返回 0,无论它从哪里运行。这发生在活动行和注释掉的行中,方法略有不同。在这个例子中它应该返回 5。不知道出了什么问题。
JSFiddle:http: //jsfiddle.net/mrengy/h2DZG/1/