javascript - Angular中form表单中input自动响应回车事件

查看:128
本文介绍了javascript - Angular中form表单中input自动响应回车事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

Angular版本v1.5.8,看如下代码:

<body>
    <div ng-controller="ctrl">
        <form>
            <input type="text">
            <button ng-click="ch()">点击</button>
        </form>
    </div>
    <script type="text/javascript">
        var app = angular.module("app", []);
        
        app.controller("ctrl", function($scope) {
            $scope.ch = function() {
                console.log("hello world");
            };
        });
    </script>
</body>

当你聚焦输入框的时候,按回车,神奇的事情发生了:控制台竟然输出hello world,这意味着angular捕获了input的回车事件,并且用button的处理器来处理。然而,如果你把<button ng-click="ch()">点击</button>换成<div ng-click="ch()">点击</div>,就没有我说的这种现象了。

请教高手来解答下,这究竟是什么原因导致的?

解决方案

这是表单默认提交动作,跟ng无关。

如楼上所说将button,type改成非'submit',或者不用form。

扩展来说其实这个问题很多人没搞清,我这里来总结以下吧~

Attributes for form submission can be specified both on form elements and on submit buttons (elements that represent buttons that submit forms, e.g. an input element whose type attribute is in the Submit Button state).

表单的提交行为,可以用两种方式定义,一是form表单自身,二是form表单的button元素(包括type='submit'的input标签,以及type='submit'的button元素,button默认type为submit)

而按enter键会触发form表单提交,这称为隐式提交。这是为了让那些使用辅助阅读工具使用者(比如屏幕阅读器)或不方便使用鼠标者所设立的

There are pages on the Web that are only usable if there is a way to implicitly submit forms, so user agents [browsers] are strongly encouraged to support this

当用户在一个表单的input标签按enter按钮时,浏览器会找到表单中的第一个提交按钮(submit button),并触发click,同时提交表单。
如果一个表单里没有任何submit button。当这个表单只有一个input元素时,在这个input标签按enter键会隐式触发表单提交,
但表单有多个input标签时就不会触发。

这是在标准里也有说明的:

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the enter key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button

If the form has no submit button, then the implicit submission mechanism must do nothing if the form has more than one field that blocks implicit submission, and must submit the form element from the form element itself otherwise.

For the purpose of the previous paragraph, an element is a field that blocks implicit submission of a form element if it is an input element whose form owner is that form element and whose type attribute is in one of the following states: Text, Search, URL, Telephone, E-mail, Password, Date and Time, Date, Month, Week, Time, Local Date and Time, Number

更多信息查阅-form表单

这篇关于javascript - Angular中form表单中input自动响应回车事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆