我试图创建一个事件,该事件在按下某个键时执行功能。我添加了一个eventListener
,它查找一个keypress === 13
(输入键),但是它并不令人担忧,并且控制台上没有错误消息。在我看来,我的eventListener
可以访问我的函数addItem,该函数在全局范围内。我真的不知道为什么它不起作用。
HTML:
<div class="container w-25">
<div class='header'>
<input class='mt-50' type='text' id='myInput' placeholder='Add a to-do'>
<button id='btn' type='button'>Add</button>
</div>
<div class='content'>
<ul id='list'>
<li>Clean cauldron</li>
<li>Beat Drago</li>
<li>Study for B.U.S.E.</li>
<li>Win quidditch cup</li>
</ul>
</div>
</div>
JavaScript:
let close = document.getElementsByClassName('close');
let btn = document.getElementById('btn');
let myList = document.getElementsByTagName('li');
let myInput = document.getElementById('myInput');
for (let i = 0; i < myList.length; i++) {
let span = document.createElement('span');
let cross = document.createTextNode('\u00D7');
span.className = 'close';
span.appendChild(cross);
myList[i].appendChild(span);
}
for (let i = 0; i < close.length; i++) {
close[i].addEventListener('click', function() {
let div = this.parentElement
div.style.display = 'none';
})
}
btn.addEventListener('click', addItem);
function addItem() {
let li = document.createElement('li');
let myInput = document.getElementById('myInput').value;
let newText = document.createTextNode(myInput)
li.appendChild(newText);
if (myInput === ''){
alert('enter a to-do please')
}else{
document.getElementById('list').appendChild(li);
}
let span = document.createElement('span');
let cross = document.createTextNode('\u00D7');
span.className = 'close';
span.appendChild(cross);
li.appendChild(span);
let close = document.getElementsByClassName('close');
for (let i = 0; i < close.length; i++)
close[i].addEventListener('click', function() {
let div = this.parentElement
div.style.display = 'none';
});
}
btn.addEventListener('click', function() {
document.getElementById('myInput').value= '';
});
myInput.addEventListener('keydown', function(e) {
if (e.keycode === 13) {
addItem();
};
});
最佳答案
document.onkeypress = function (e) {
if (e.keyCode == 13) {
alert("Enter pressed!");
}
};
<h1>Hello, World!</h1>