如何在ng-hover事件中传递元素的ID?

时间:2016-09-09 18:20:48

标签: javascript jquery angularjs

我有一个像这样的元素:

<div id="one" ng-mouseover="showDefinition()"> Some Text</div>
<div id="one" ng-mouseover="showDefinition()"> Some Text</div>
<div id="one" ng-mouseover="showDefinition()"> Some Text</div>

当我将鼠标悬停在每个相应元素上时,会触发showDefinition函数:

    scope.showDefinition = function showDefinition() {
        console.log("youve hovered over the id : + <element's id>");
        }

如何传入触发悬停的元素ID?

4 个答案:

答案 0 :(得分:3)

scope.showDefinition = function showDefinition(e) {
  console.log("you've hovered over the id" : + e.target.id);
}

并在HTML中

<div id="one" ng-mouseover="showDefinition($event)"> Some Text</div>

Plunkr https://plnkr.co/edit/CW9kXLzc23xcWlA5EJzm?p=preview

答案 1 :(得分:2)

Jim Cote是对的,您可以将$event传递给您的ng-mouseover,如下所示:

<div id="one" ng-mouseover="showDefinition($event)"> Some Text</div>

$event documentation

$ event基本上是jquery (or jqlite) event object

您还需要确保不要在html中重复使用id,因为这样会搞砸。

您的代码最终可能是这样的:

<div id="one" ng-mouseover="showDefinition($event)"> Some Text</div>
<div id="two" ng-mouseover="showDefinition($event)"> Some Text</div>
<div id="three" ng-mouseover="showDefinition($event)"> Some Text</div>



scope.showDefinition = function showDefinition(event) {
    console.log("youve hovered over the id :" + event.target.id);
}

答案 2 :(得分:1)

您可以将其作为参数本身传递:)甚至不需要event对象

<div id="one" ng-mouseover="showDefinition('one')"> Some Text</div>
<div id="two" ng-mouseover="showDefinition('two')"> Some Text</div>

在控制器中,

scope.showDefinition = function showDefinition(id) {
    console.log("youve hovered over the id : " + id);
}

https://plnkr.co/edit/OxM5PE4gNtSzpVLnz7Tm?p=preview

答案 3 :(得分:0)

附加工作代码段

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.showDefinition = function showDefinition($event) {
        console.log("youve hovered over the id :" + $event.target.id);
        }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="one" ng-mouseover="showDefinition($event)"> Some Text</div>
<div id="two" ng-mouseover="showDefinition($event)"> Some Text</div>
<div id="three" ng-mouseover="showDefinition($event)"> Some Text</div>
  </div>
&#13;
&#13;
&#13;

相关问题