0
我想写一个自动完成的小部件。这些要求要求水平规则元素划分列表的各个部分。这个小时,特别是任何李将打破所选项目的正确突出显示。jquery跳过选择器中的元素时,不匹配选择器的元素添加到ul
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 {背景色:红色; }
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元素后箭头就会打破。当你经过有问题的李元素时,箭头也会被打破。
我很难过我做错了什么。
请在您的问题中发布一个完整的代码示例。 – j08691
jsbin无法正常工作吗? –
它可能工作,但您需要先在您的问题中发布您的代码。像jsbin,jsfiddle等网站可以补充您的问题中的代码,绝不应该是它的唯一来源。如果jsbin无法访问会发生什么。 – j08691