我有與從數據庫獲取的數據動態地填充<li>
列表元素的<ul>
無序列表使用JQuery阿賈克斯功能導航:如何動態填充li元素之間使用向上或向下鍵
<ul id="here">
<li>Product1</li>
<li>Product2</li>
<li>Product3</li>
<li>Product4</li>
<li>Product5</li>
<li>Product6</li>
</ul>
我可以懸停在這些使用以下CSS代碼:
#here{
position: fixed;
background-color: white;
width:175px;
height:300px;
border: 1px solid grey;
display:none;
padding:0px 0px 10px 10px;
}
#here li:hover {
background: #ccc;
cursor: pointer;
}
的JavaScript和JQuery用於填充<li>
元素寫入是:
var pr= ["Product1", "Product2", "Product3", "Product4", "Product5", "Product6"];
for (var option in pr) {
var newLi = document.createElement("li");
newLi.innerHTML=pr[option];
$("#here").append(newLi);
}
但我需要能夠使用鍵盤向上和向下鍵在這些<li>
元素之間上下移動。任何人都可以指導我如何做到這一點?
點擊,您能解釋一下你的代碼的以下部分: 'currentFocus + = e.keyCode === 38? -1:1; currentFocus <0 &&(currentFocus = children.length - 1); currentFocus> = children.length &&(currentFocus = 0);' – UmarAbbasKhan
第一行:如果按下'Arrow Up(38)',則將當前索引減1,否則增加它。接下來的兩行確保你不會有索引超出範圍。如果它小於'0',則將其設置爲'length - 1',如果它是'length'或更大,則將其設置爲'0' – Christoph
較長版本的兩行將爲:if(currentFocus <0)currentFocus = children.length - 1; if(currentFocus> = children.length)currentFocus = 0;' – Christoph