标签上的 Angular.js ng-click 事件触发了两次 [英] Angular.js ng-click events on labels are firing twice

查看:29
本文介绍了标签上的 Angular.js ng-click 事件触发了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码使用 angular.js

Given the following code using angular.js

Plunkr 在这里:http://plnkr.co/edit/i4MAzs

Plunkr here: http://plnkr.co/edit/i4MAzs

HTML:

<form name="myForm" ng-controller="Ctrl">
  Try clicking on the labels. <br/>
  <label>
    Value1: <input type="checkbox" ng-checked='value1' ng-click='toggleValue1()'>
  </label> <br/>
  <label ng-click='toggleValue2()'>
    Value2: <input type="checkbox" ng-checked="value2">
  </label> <br/>
  <tt>value1 = {{value1}}</tt><br/>
  <tt>value2 = {{value2}}</tt><br/>
  <tt>fire_count = {{fire_count}}</tt>
</form>

Javascript:

Javascript:

angular.module('App', []);

function Ctrl($scope) {
  $scope.value1 = true;
  $scope.value2 = 'YES'
  $scope.fire_count = 0;

  $scope.toggleValue1 = function(){
    $scope.value1 = !$scope.value1;
    $scope.fire_count++;
    console.log("Clicked!");
  }

  $scope.toggleValue2 = function(){
    $scope.value2 = !$scope.value2;
    $scope.fire_count++;
    console.log("Clicked!");
  }
}

当您单击Value2"标签时,单击事件将触发两次.这仅在 ng-click 附加到标签时发生.当它附加到输入元素时,一切都按预期工作.

The click event will fire twice when you click on the 'Value2' label. This only happens when ng-click is attached to the label. When it's attached to the input element everything works as expected.

谁能解释一下这是怎么回事?

Can someone explain what's going on?

推荐答案

看看这个答案:

https://stackoverflow.com/a/17185362/3093703

此外,我已编辑您的 plnkr 以显示事件目标:

Also, I've edited your plnkr to show the event target:

http://plnkr.co/edit/73aslwHnwVcTd2fxSJ0f?p=preview

input 和 label 元素都在接收事件.

Both the input and label elements are receiving the event.

为避免这种情况,您可以在执行任何操作之前检查事件目标的标签名称.

To avoid this, you can check the tag name of the event target before performing any action.

编辑

至于为什么会这样:标签实际上以 div 或其他元素不会的方式绑定到输入元素.输入被称为标签的标签控件.

As to why this is: the label is actually tied to the input element in a way the div's or other elements would not be. The input is called the label's labeled control.

当您在标签上触发操作时,该操作也会在标签控件上运行:

When you trigger an action on a label, that action is also run on the labeled control:

例如,在点击复选框标签检查复选框的平台上,点击以下代码段中的标签可能会触发用户代理在输入元素上运行合成点击激活步骤,就好像元素本身已被用户

For example, on platforms where clicking a checkbox label checks the checkbox, clicking the label in the following snippet could trigger the user agent to run synthetic click activation steps on the input element, as if the element itself had been triggered by the user

这篇关于标签上的 Angular.js ng-click 事件触发了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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