javascript - Angular中form表单中input自动响应回车事件
高洛峰
高洛峰 2017-04-11 08:59:13
[JavaScript讨论组]

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

<body>
    <p ng-controller="ctrl">
        <form>
            <input type="text">
            <button ng-click="ch()">点击</button>
        </form>
    </p>
    <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>换成<p ng-click="ch()">点击</p>,就没有我说的这种现象了。

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
高洛峰

这是表单默认提交动作,跟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表单

巴扎黑

button默认的type是submit,点回车就触发了提交,你把<button ng-click="ch()">点击</button>改成<button type='button' ng-click="ch()">点击</button>就好了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号