AngularJs ng-click $event 将子元素作为目标传递 [英] AngularJs ng-click $event passes child element as target
问题描述
对于表格中的每个 td 元素,我都有一个附加的 ng-click.这是每个表格单元格的(简化)html:
For each td element in a table I have an attached ng-click. Here is the (simplified) html for each table cell:
<td ng-click="cellClicked($event)">
<span ng-if="!cellEdit">{{event.eventName}}</span>
<input type="text" ng-if="cellEdit" ng-model="event.eventName">
</td>
还有我的(简化的)ng-click 功能:
And my (simplified) ng-click function:
scope.cellClicked = function (event) {
rowScope.cellEdit = true
angular.element(event.target).find('input').focus()
}
我的目标是:
- 用户点击表格单元格
- 单元格更改为编辑模式"
- 将焦点放在 td 内的 input 元素上.
- User clicks a table cell
- Cell changes to "edit mode"
- Give focus to the input element located inside the td.
现在只要用户点击在 td 元素内而不是在 span 元素上,这就会起作用:
Right now this is working as long as the user clicks inside the td element but not on the span element:
console.log(angular.element(event.target)) #--> [td...] (as desired)
但是,如果用户点击 td 中的 span 元素:
However if the user clicks on the span element within the td:
console.log(angular.element(event.target)) #--> [span...]
在此用例中,分配焦点不起作用.我希望访问 span 的父元素,执行如下操作:
In this use case assigning focus does not work. I was hoping to access the parent element of the span doing something like:
angular.element(event.target.closest('td'))
或
angular.element(event.target.parentNode)
但是当一个元素通过 $event 传递并访问时,它会出现,没有父上下文.
But it appears when an element gets passed through via $event and accessed there is no parent context.
我该怎么做:
- 防止点击 span 元素触发 td 的 ng-click
- 点击 span 元素通过它的 html 父元素
- Prevent clicking the span element firing the td's ng-click
- On click of span element pass through it's html parent
推荐答案
变化:
angular.element(event.target)
到:
angular.element(event.currentTarget)
解决了我的问题.
在我看来,使用 event.currentTarget 比使用 event.target 在大多数用例中.
It seems to me using event.currentTarget is preferred to event.target in the majority of usage cases.
这篇关于AngularJs ng-click $event 将子元素作为目标传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!