gpt4 book ai didi

angularjs - 为什么在 AngularJS 表单的文本输入中按 Enter 会导致副作用?

转载 作者:行者123 更新时间:2023-12-04 02:37:53 25 4
gpt4 key购买 nike

Live Demo

考虑以下形式:

<form>
<div>
<label>Status: </label>
<button ng-repeat="status in statuses"
class="btn btn-default"
ng-model="job.status.id" btn-radio="status.id">
{{ status.name }}
</button>
</div>
<div>
<label>Name: </label>
<input type="text" ng-model="job.name">
</div>
</form>

当焦点位于名称字段并按下 Enter 键时,由于某种原因,状态设置为“全部正常”。 Live Demo

为什么会这样?我怎么能阻止这种副作用?

最佳答案

从 ngForm 文档:

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)

if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit

if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit)


button 的默认类型元素是“提交”( <button></button> === <button type="submit"></button> )。因此,当您按 Enter 键时,第一个按钮将被提交。

要补救,只需输入 type="button"在你的按钮上。
<button 
ng-repeat="status in statuses"
class="btn btn-default"
ng-model="job.status.id"
btn-radio="status.id"
type="button"
>
{{ status.name }}
</button>

关于angularjs - 为什么在 AngularJS 表单的文本输入中按 Enter 会导致副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com