这一次...我正在尝试创建一个函数,其中元素应该在用户按下 Enter 键时显示。但是,按键功能不起作用。
$(document).keypress(function(e) {
if(e.which == 13) {
if (inputBox.value === "")
{
alert("Write plz");
}
else
{
let li = document.createElement("li");
li.innerHTML = inputBox.value;
list_li.appendChild(li);
}
}});
您的脚本可使用这些字段并加载 jQuery
const list_li = document.getElementById("list_li");
const inputBox = document.getElementById("inputBox");
$(document).keypress(function(e) {
if (e.which == 13) {
if (inputBox.value === "") {
alert("Write plz");
} else {
let li = document.createElement("li");
li.innerHTML = inputBox.value;
list_li.appendChild(li);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<input type="text" id="inputBox" value="" />
<ul id="list_li"></ul>
如果该字段位于表单中,则需要preventDefault,并且只需将事件处理程序分配给提交事件即可,而无需测试键。
这里根本不需要 jQuery
window.addEventListener("DOMContentLoaded", () => { // when page has loaded
const list_li = document.getElementById("list_li");
const inputBox = document.getElementById("inputBox");
document.getElementById("myForm").addEventListener("submit", (e) => {
e.preventDefault();
const value = inputBox.value.trim();
if (value === "") {
alert("Write plz");
return;
}
let li = document.createElement("li");
li.innerHTML = inputBox.value;
list_li.appendChild(li);
inputBox.value = "";
});
});
<form id="myForm">
<input type="text" id="inputBox" value="" />
</form>
<ul id="list_li"></ul>