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



我有一个元素,像这样:

<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 ?

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

Jim Cote是对的,你可以像这样将$event传递给你的ng-mouseover:

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

美元事件文档

$event基本上是一个jquery(或jqlite)事件对象。

你还需要确保你不会在你的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);
}

你可以把它作为参数传递:)甚至不需要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 =预览

附工作代码片段

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

最新更新