我正在尝试编写自动完成小部件。要求要求划分列表部分的水平规则元素。此hr,特别是任何li将打破所选项目的正确突出显示。
https://jsbin.com/rofohe/edit?html,console,output
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Autocomplete sandbox for selection highlighting: simple elements; adding a li element that doesn't match the selector will break the navigation.
<br>
Type Here:<input type="text" id="textbox1"/>
<ul role="presentation">
<li role="presentation" class="">
<button >A</button>
</li>
<li role="presentation" class="">
<button >B</button>
</li>
<li role="presentation" class="">
<button >C</button>
</li>
<li role="presentation" class="">
<button>D</button>
</li>
<!-- <li> <hr class="fab-rule--black"> </li> <li> nothing </li>-->
<li role="presentation" class="">
<button >A1</button>
</li>
<li role="presentation">
<button >B1</button>
</li>
<li role="presentation" class="">
<button>C1</button>
</li>
<li role="presentation">
<button >D1</button>
</li>
<li role="presentation" class="">
<button >E1</button>
</li>
</ul>
<div id="log">
</div>
</body>
</html>
CSS: .selected {background-color:red; }
JS:
$("#textbox1").keyup(function(){
var $autocompleteElements = $("ul li[role='presentation']"),
$autocompleteSelected = $("ul li.selected"),
autocompleteSelectedIndex = $autocompleteSelected.index();
console.log("autocompleteselectedindex:"+autocompleteSelectedIndex);
$autocompleteSelected.removeClass('selected');
switch (event.keyCode) {
//They pressed the up arrow
case 38:
//add the selected class on the prev array item
if (autocompleteSelectedIndex == -1) {autocompleteSelectedIndex =0;}
$autocompleteElements.eq(autocompleteSelectedIndex - 1).addClass("selected");
break;
//They pressed the down arrow
case 40:
if (autocompleteSelectedIndex == $autocompleteElements.length) { autocompleteSelectedIndex = $autocompleteElements.length -1; }
//add the selected class on the next array item
$autocompleteElements.eq(autocompleteSelectedIndex + 1).addClass("selected");
break;
//They pressed the Esc key
case 27:
$firstAutocompleteSelectedChild = $($($autocompleteSelected[0]).children()[0]);
//if the selected item is a link, execute the link
if ( $firstAutocompleteSelectedChild.is("a") ) {
window.location = $firstAutocompleteSelectedChild.attr("href");
} else { //assumes we are a button
//if the selected item was a normal selection, put the search query in the search input ..
$target.closest("[data-search-form]").find("[data-search-input]").val(
$firstAutocompleteSelectedChild.attr("data-search-input")
);
//..and close the autocomplete panel
closePanel(target);
}
break;
}
});
将光标放在输入框中并向上/向下箭头。您应该能够毫无问题地遍历元素。现在拉出一个已注释掉的li元素,并将其插入注释掉的片段下方。箭头导航不再有效。箭头经过刚刚添加的li元素后,箭头会中断。当您经过有问题的li元素时,向上箭头也会被打破。
我很难过我做错了什么。
答案 0 :(得分:0)
jQuery中的索引似乎有一个范围组件。改变
autocompleteSelectedIndex = $autocompleteSelected.index();
到
autocompleteSelectedIndex = $autocompleteElements.index($autocompleteSelected);
解决了这个问题。