单击表单中的按钮会导致页面刷新 [英] Clicking a button within a form causes page refresh

查看:28
本文介绍了单击表单中的按钮会导致页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 表单,里面有两个按钮标签.ng-click 一键提交表单.另一个按钮纯粹用于使用 ng-click 进行导航.但是,当单击第二个按钮时,AngularJS 会导致页面刷新,从而触发 404.我在函数中放置了一个断点,它正在触发我的函数.如果我执行以下任何操作,它就会停止:

  1. 如果我删除 ng-click,按钮不会导致页面刷新.
  2. 如果我注释掉函数中的代码,它不会导致页面刷新.
  3. 如果我使用 href="" 将按钮标记更改为锚标记 (),则不会导致刷新.立>

后者似乎是最简单的解决方法,但为什么 AngularJS 甚至在我的函数之后运行任何导致页面重新加载的代码?好像是个bug.

表格如下:

<字段集><div class="control-group"><label class="control-label" for="passwordButton">密码</label><div class="控件"><button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">更改</button>

</fieldset></表单>

这是控制器方法:

$scope.showChangePassword = function() {$scope.selectedLink = "更改密码";};

如果您查看 W3C 规范,当您不希望它们提交时,尝试使用 type='button' 标记您的按钮元素似乎是显而易见的事情.>

要特别注意的是它说的地方

<块引用>

未指定 type 属性的 button 元素与 type 属性设置为 "submit" 的 button 元素表示相同的事物

I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:

  1. If I remove the ng-click, the button doesn’t cause a page refresh.
  2. If I comment out the code in the function, it doesn’t cause a page refresh.
  3. If I change the button tag to an anchor tag (<a>) with href="", then it doesn’t cause a refresh.

The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.

Here is the form:

<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="passwordButton">Password</label>
      <div class="controls">
        <button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
      </div>
    </div>

    <div class="buttonBar">
      <button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
    </div>
  </fieldset>
</form>

Here is the controller method:

$scope.showChangePassword = function() {
  $scope.selectedLink = "changePassword";
};

解决方案

If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button' when you don't want them to submit.

The thing to note in particular is where it says

A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"

这篇关于单击表单中的按钮会导致页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆