使用JavaScript按下回车键时调用函数
Calling a function when enter key is pressed with JavaScript
我正在使用addEventListener
将事件绑定到节点。addEventListener
向节点添加addItem
功能。但当我按下回车键时,该功能没有运行。
这是JavaScript:
document.getElementById('add-item').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
//1. Empty the Input field once the item
document.getElementsByTagName('input')[0].value = '';
}
这是HTML:
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
另一方面,该功能与click
一起运行
document.getElementById('add-item').addEventListener('click', addItem, false);
我想用JavaScript做这件事,只是不使用jQuery库。
编辑:我想将事件附加到输入字段。
我愿意打赌,当您按enter键时,add-item
元素没有聚焦。相反,请尝试将触发器更改为输入字段。
document.getElementById('new-item-text').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量