Command + Enter提交表格

    技术2022-07-11  108

    I've used Mac's for about six years now but it wasn't until I started using Tweetdeck that I realized how awesome the [COMMAND]+[ENTER] key combination was.  Inside a textarea?  No problem -- [COMMAND]+[ENTER] and the form is submitted.  What if all forms could be that way?  They can be with a little JavaScript!

    我已经使用Mac大约六年了,但是直到我开始使用Tweetdeck时,我才意识到[COMMAND]+[ENTER]组合[COMMAND]+[ENTER]有多棒。 在文本区域内? 没问题- [COMMAND]+[ENTER]并提交表格。 如果所有形式都可能那样呢? 他们可以使用一些JavaScript!

    JavaScript (The JavaScript)

    There are two routes to go:  adding an event listener to the form (event delegate), or applying an event listener to specific textarea elements.  The safer route is event delegation, as dynamic forms can have many textareas added at any time, but per-textarea assignments are much more efficient. Ultimately it's up to the developer to know their form.  Here are three code samples to accomplish form submission in a variety of ways:

    有两种方法:将事件侦听器添加到窗体(事件委托),或将事件侦听器应用于特定的textarea元素。 比较安全的方法是事件委托,因为动态表单可以随时添加许多文本区域,但是按文本区域分配则效率更高。 最终,由开发人员知道其形式。 以下是三个代码示例,可以通过多种方式完成表单提交:

    // Assign to individual textarea (most efficient) myTextarea.addEventListener('keydown', function(e) { if(e.keyCode == 13 && e.metaKey) { this.form.submit(); } }); // Form event delegation - individual form (somewhat efficient) form.addEventListener('keydown', function(e) { if(!(e.keyCode == 13 && e.metaKey)) return; var target = e.target; if(target.form) { target.form.submit(); } }); // Body event delegation - any form (least efficient) document.body.addEventListener('keydown', function(e) { if(!(e.keyCode == 13 && e.metaKey)) return; var target = e.target; if(target.form) { target.form.submit(); } });

    Tweetdeck uses [COMMAND]+[ENTER] as does GitHub on some of their forms.  I've naturally started checking for this key command combo instead of tabbing to a field which will submit the form via traditional [ENTER] key.

    Tweetdeck和GitHub在某些形式上使用[COMMAND]+[ENTER] 。 我自然已经开始检查此键盘命令组合,而不是使用制表符查看将通过传统的[ENTER]键提交表单的字段。

    翻译自: https://davidwalsh.name/command-enter-submit-forms

    Processed: 0.024, SQL: 9