如何将基于enter键的事件分配给选定的<<ul>内的元素

How to allocate an enter key based event to a selected <li> element within <ul>

本文关键字:ul 元素 分配 enter 事件      更新时间:2023-09-26

我有以下<ul>无序列表元素:

<ul id="here"></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,
#here li.--focus {
  background: #ccc;
  cursor: pointer;
}

我正在用<li>元素动态地填充这个<ul>元素,这些元素是使用JQuery .ajax()从数据库中获取的产品名称。只有在填充<ul>元素时才会看到它。否则显示为none。我也可以使用上下键在<li>元素之间导航。

填充<ul>元素的代码是:
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>元素之间导航的代码是:

$(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"); 
  }
});

我想在选定的<li>元素上附加一个事件,并在<ul>元素可见的情况下按键盘上的按钮输入时执行一个具有<li>元素值的函数。

我尝试了以下函数,但它不起作用:

$("#here").on("keypress", function(e) { alert("some key pressed");}) 

所以,如果#这里没有注册任何函数执行在任何按键,我怎么能让它识别其他任何东西?

谁能指导我怎么做这个?

以上代码的演示

继续您的示例:对不起,我使用了jQuery,我赶时间。但是,简单地说,当按下输入按钮时,找到具有类焦点的li。然后获取该列表项的内容并对其进行处理

https://jsfiddle.net/nhdabq4x/

// When ENTER is pressed
if (e.keyCode === 13) {
  e.preventDefault();
  // For each li, 
  $('li').each(function() {
    // Check it if has class "--focus"
    if($(this).hasClass('--focus')) {
      // If it does, do something with it!
      $('.product-chosen').text($(this).text())
    };
  });
};

我会使用更多的jQuery。可能无法解决"按键"的问题。尝试使用'keydown'事件,并在其他元素上测试它,以排除ul元素的潜在问题。

// Add the function to the 'ul'
$('#here').on('kedown', function(e) {
    if (e.keyCode === 38 || e.keyCode === 40) {
        e.preventDefault();
    var focused = $('#here .--focus');
    if( focused === undefined )  // no earlier selection, select first
        $('#here li:first').addClass('--focus');

    if( e.keyCode === 38 ) {  // up arrow
        // toggle focus class for selected element and the element above
        var previous = $(focused).prev();
        focused.toggleClass('--focus');
        previous.toggleClass('--focus');
    } else if( e.keyCode === 40 ) { // down arrow
        // toggle focus class for selected element and the element below
        var next = $(focused).next();
        focused.toggleClass('--focus');
        next.toggleClass('--focus');
    }
    // consider adding an else clause that prints a debug message to test this function
}