how to navigate between dynamically populated li e

2019-09-10 23:36发布

问题:

I have an <ul> unordered list with dynamically populated <li> list elements with data taken from database using JQuery .ajax function:

<ul id="here">
<li>Product1</li>
<li>Product2</li>
<li>Product3</li>
<li>Product4</li>
<li>Product5</li>
<li>Product6</li>
</ul>

I can hover over these using following css code:

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

The Javascript and JQuery written for populating the <li> elements is:

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

but I need to be able to move up and down among these <li> elements using keyboard up and down keys. Can anyone guide me how can I do this?

回答1:

Using a CSS helper class --focus for this:

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>



回答2:

You can try something like that -

in order to make the li focusable it should have a tabindex.

You can add an event listener to the ul capturing clicks on 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();
        }
});