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