javascript Angular ng-click $event 将子元素作为目标传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29421360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular ng-click $event passes child element as target
提问by Cumulo Nimbus
For each tdelement in a table I have an attached ng-click. Here is the (simplified) html for each table cell:
对于表中的每个td元素,我都有一个附加的 ng-click。这是每个表格单元格的(简化)html:
<td ng-click="cellClicked($event)">
<span ng-if="!cellEdit">{{event.eventName}}</span>
<input type="text" ng-if="cellEdit" ng-model="event.eventName">
</td>
And my (simplified) ng-click function:
还有我的(简化的)ng-click 功能:
scope.cellClicked = function (event) {
rowScope.cellEdit = true
angular.element(event.target).find('input').focus()
}
Its my goal to:
我的目标是:
- User clicks a table cell
- Cell changes to "edit mode"
- Give focus to the inputelement located inside the td.
- 用户单击表格单元格
- 单元格更改为“编辑模式”
- 将焦点放在td内的input元素上。
Right now this is working as long as the user clicks inside the td element but not on the span element:
现在,只要用户在 td 元素内部单击而不是在 span 元素上单击,这就会起作用:
console.log(angular.element(event.target)) #--> [td...] (as desired)
However if the user clicks on the span element within the td:
但是,如果用户单击 td 中的 span 元素:
console.log(angular.element(event.target)) #--> [span...]
In this use case assigning focus does not work. I was hoping to access the parent element of the spandoing something like:
在此用例中,分配焦点不起作用。我希望访问跨度的父元素,执行以下操作:
angular.element(event.target.closest('td'))
or
或者
angular.element(event.target.parentNode)
But it appears when an element gets passed through via $event and accessed there is no parent context.
但是当一个元素通过 $event 传递并访问时,它就会出现,没有父上下文。
How can I either:
我怎样才能:
- Prevent clicking the spanelement firing the td's ng-click
- On click of spanelement pass through it's html parent
- 防止单击span元素触发td的 ng-click
- 单击span元素通过它的 html 父级
回答by Cumulo Nimbus
Changing:
改变:
angular.element(event.target)
to:
到:
angular.element(event.currentTarget)
fixed my issue.
修复了我的问题。
It seems to me using event.currentTargetis preferred to event.targetin the majority of usage cases.
在我看来,在大多数用例中,使用event.currentTarget比使用event.target更受欢迎。
回答by dfsq
event.target.closest('td')
won't work because event.target
is a DOM element and it doesn't have method closest
. You need to create a jQuery object to use this method.
event.target.closest('td')
不会工作,因为它event.target
是一个 DOM 元素并且它没有 method closest
。您需要创建一个 jQuery 对象才能使用此方法。
Try to find closest td
like this:
尝试td
像这样找到最接近的:
angular.element(event.target).closest('td')
回答by David Dehghan
In Angular 7.x
在 Angular 7.x 中
myClickHandler($event) {
this.selectedElement = <Element>$event.target.closest('.list-item');
}
html:
html:
<div class="list-item" (click)="myClickHandler($event)">...</div>