gpt4 book ai didi

javascript - 如何将基于输入键的事件分配给
    中选定的
  • 元素

转载 作者:行者123 更新时间:2023-11-28 05:09:16 25 4
gpt4 key购买 nike

我有以下 <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;
}

我正在填充这个 <ul>带有 <li> 的元素动态元素是使用 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> 上附加一个事件元素并执行值为 <li> 的函数如果 <ul> 按下按钮,则在键盘上输入元素元素可见。

我尝试了以下功能,但它不起作用:

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

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

谁能指导我如何做到这一点?

Demo for above code

最佳答案

继续您的示例:抱歉,我使用了 jQuery,我很匆忙。但简单地说,在按下回车按钮时找到具有类 --focus 的 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())
};
});
};

关于javascript - 如何将基于输入键的事件分配给 <ul> 中选定的 <li> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39659426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com