检查是否单击了div或其子项之一

时间:2015-10-13 11:41:38

标签: javascript html angularjs

我有一个div如下

<div class="parent">
    <!--several child divs now-->
</div>

现在,我已经使用AngularJS在body上注册了一个click处理程序,如下所示:

HTML:

<body ng-click="registerClick($event)">
</body>

控制器:

$scope.registerClick(e) {
   //Here check if the parent div or one of its children were clicked
}

如何,可以在我的处理程序中使用$event来确定div是否具有类&#39; parent&#39;或者其中一个孩子被点击了?

2 个答案:

答案 0 :(得分:3)

将其更改为:

$scope.registerClick(e) {
    if (e.target.classList.contains('parent')){
        // The .parent div is clicked
    } else if (e.target.parentNode.classList.contains('parent')){
        // Some child of the .parent div is clicked
    } else {
        var elem = e.target;

        while(elem.tagName != 'body' || !elem.classList.contains('parent')){
            elem = elem.parentNode;
        }

        if (elem.classList.contains('parent')){
            console.log('DIV .parent')
        } else {
            console.log('Body tag reached. No .parent element found');
        }
    }
}

e.target是点击的元素。用它来确定单击了哪个元素。这是一个干净的JavaScript解决方案。如果可以附加事件,你甚至不需要$scope.registerClick(e) {部分:

someDiv.onclick = function(){/* Same code as above. */}

如果您使用后一种方法,'this'指向div,那么您可以稍微验证一下。

答案 1 :(得分:0)

您可以执行类似

的操作

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.registerClick = function($event) {
    //if has jQuery
    if ($($event.target).closest('.parent').length) {
      console.log('clicked parent');
      $scope.jQuery = true;
    } else {
      $scope.jQuery = false;
    }

    var isParent = false;
    if (angular.isFunction($event.target.closest)) {
      isParent = !!$event.target.closest('.parent');
    } else {
      var tmp = $event.target;
      do {
        isParent = tmp.classList.contains('parent');
        tmp = tmp.parentNode;
      } while (tmp && tmp.classList && !isParent);
    }
    $scope.native = isParent;
  };
})
.parent {
  border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="my-app">
  <div ng-controller="AppController" ng-click="registerClick($event)">
    <div>outside</div>
    <div class="parent">
      parent
      <div>div</div>
      <div>div</div>
    </div>

    <div>
      jQuery: {{jQuery}}
    </div>
    <div>
      native: {{native}}
    </div>
  </div>
</div>