Angular.js NG-点击标签事件被触发两次 [英] Angular.js ng-click events on labels are firing twice

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

问题描述

由于使用angular.js以下code

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!");
  }
}

当你点击'值'标签上的单击事件将触发两次。当NG-点击连接到标签这只发生。当它连接到输入元素一切正常。

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?

推荐答案

在这个答案请看下图:

<一个href=\"http://stackoverflow.com/a/17185362/3093703\">http://stackoverflow.com/a/17185362/3093703

另外,我编辑过plnkr显示事件目标:

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

<一个href=\"http://plnkr.co/edit/73aslwHnwVcTd2fxSJ0f?p=$p$pview\">http://plnkr.co/edit/73aslwHnwVcTd2fxSJ0f?p=$p$pview

两者的输入和标签元件接收事件。

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的或其它元件将不依赖于所述输入元件。该输入被称为标签的<一href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#labeled-control\">labeled控制。

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-点击标签事件被触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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