2016-09-22 89 views
0

我有與從數據庫獲取的數據動態地填充<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>元素之間上下移動。任何人都可以指導我如何做到這一點?

回答

2

使用CSS輔助類--focus此:

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); 
 
} 
 

 
var currentFocus; 
 

 
$(document).on("keyup", function(e) { 
 
    if (e.keyCode === 38 || e.keyCode === 40) { 
 
    e.preventDefault(); 
 
    
 
    var children = $("#here").children(); 
 
    if (currentFocus === undefined) { 
 
     currentFocus = 0; 
 
    } else { 
 
     currentFocus += e.keyCode === 38 ? -1 : 1; 
 
     currentFocus < 0 && (currentFocus = children.length - 1); 
 
     currentFocus >= children.length && (currentFocus = 0); 
 
    } 
 
    children.removeClass("--focus"); 
 
    children.eq(currentFocus).addClass("--focus"); 
 
    } 
 

 
});
#here { 
 
    background-color: white; 
 
    width: 175px; 
 
    height: 300px; 
 
    border: 1px solid grey; 
 
    padding: 0px 0px 10px 10px; 
 
} 
 
#here li:hover, 
 
#here li.--focus { 
 
    background: #ccc; 
 
    cursor: pointer; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="here"> 
 
</ul>

+0

點擊,您能解釋一下你的代碼的以下部分: 'currentFocus + = e.keyCode === 38? -1:1; currentFocus <0 &&(currentFocus = children.length - 1); currentFocus> = children.length &&(currentFocus = 0);' – UmarAbbasKhan

+0

第一行:如果按下'Arrow Up(38)',則將當前索引減1,否則增加它。接下來的兩行確保你不會有索引超出範圍。如果它小於'0',則將其設置爲'length - 1',如果它是'length'或更大,則將其設置爲'0' – Christoph

+0

較長版本的兩行將爲:if(currentFocus <0)currentFocus = children.length - 1; if(currentFocus> = children.length)currentFocus = 0;' – Christoph

0

您可以嘗試類似的東西 - 爲了使李可聚焦它應該有一個的tabindex

您可以添加一個事件偵聽器捕獲UL上li

var pr= ['Product1', 'Product2', 'Product3', 'Product4', 'Product5', 'Product6']; 
$("#here").append(
    pr.map(function(product){ 
     return $('<li tabindex="0">'+product+'</li>') 
    })).on('keydown','li', function(e) { 
     if (e.keyCode == 40) {   
      $(this).next().focus(); 
     } 
     if (e.keyCode == 38) {   
      $(this).prev().focus(); 
     } 
});  
相關問題