如何让 javascript 函数在 Enter 键上运行,而不是单击?

当我单击此按钮时,它会运行该函数,一切正常。


<input id="input_listName" /><button id="btn_createList">add</button>

当我点击它时,它会运行:


$('#btn_createList').click(function(){

    $('.ul_current').append($('<li>', {

         text: $('#input_listName').val()

    }));

});

当我按下它时,它将输入中的值附加到元素<li>。


如何重做此操作,以便在单击“输入键”时运行该函数,而不是单击时运行函数?


我想把提交键全部隐藏起来。请注意,输入和提交周围没有表单标签,因为这是一个 API 应用程序,我只是想过滤而不是真正提交任何内容。


暮色呼如
浏览 105回答 4
4回答

BIG阳

不。你有一个表格。就这样对待它。document.getElementById('input_listName').addEventListener('submit', function(e) {&nbsp; e.preventDefault();&nbsp;&nbsp;&nbsp; const li = document.createElement('li');&nbsp; li.append(this.listName.value);&nbsp; document.querySelector(".ul_current").append(li);&nbsp;&nbsp;&nbsp; // optionally:&nbsp; // this.listName.value = ""}, false);<form id="input_listName">&nbsp; <input type="text" name="listName" />&nbsp; <button type="submit">add</button></form><ul class="ul_current"></ul>使其成为表单可以提供浏览器为您带来的所有好处。在桌面上,您可以按 Enter 提交。在移动设备上,虚拟键盘还可以提供快速访问提交按钮。您甚至可以required向<input />元素添加验证规则,浏览器将为您处理这一切。

眼眸繁星

我认为您想要的是检查按下了哪个键,对吗?为此,您只需检查 event.keyCode === 13所以你的代码将类似于以下内容:$('#btn_createList').keypress(function(event){&nbsp; &nbsp; if (event.keyCode === 13) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('.ul_current').append($('<li>', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;text: $('#input_listName').val()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}));&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;});希望这能起到作用!

摇曳的蔷薇

借助 的帮助event,您可以捕获按下的enter(keycode = 13) 键,如我的示例中所示。有必要吗?$('#btn_createList').keypress(function(event){&nbsp; &nbsp;if (event.keyCode == 13) {&nbsp; &nbsp; $('.ul_current').append($('<li>', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;text: $('#input_listName').val()&nbsp; &nbsp; }));&nbsp; &nbsp; }});

LEATH

<input id="input_listName" /><button id="btn_createList">add</button>此语法在技术上是错误的,您的标签以 开头<input>和结尾</button>。您还可以向函数添加一个简单的检查,如果用户没有在输入字段中输入任何内容,则不应返回任何内容。您还可以查看此备忘单以了解有关键码的更多信息https://css-tricks.com/snippets/javascript/javascript-keycodes/$('#btn_createList').keypress(function(event){&nbsp; if($('#input_listName').val()) {&nbsp; &nbsp; if (event.keyCode == 13) {&nbsp; &nbsp; $('.ul_current').append($('<li>', {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;text: $('#input_listName').val()&nbsp; &nbsp; }));&nbsp; &nbsp; }&nbsp; }});<div id="btn_createList">&nbsp; <input id="input_listName" type="text">&nbsp; <ul class="ul_current">&nbsp; </ul></div><script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript