如何在打字稿中的鼠标悬停函数中仅调用一次函数?
How to call a function only once inside mouseover function in typescript?
我正在使用 angular7。在我的应用程序中,我显示了一个地点列表。当我将鼠标悬停在任何一个地方时,我正在调用 ajax 函数将该值存储在数据库中。
但是当我将鼠标悬停在任何一个元素上时,该 ajax 函数会被调用多次。我只想调用该函数一次。
这是我的 angular 代码:
<div *ngFor="let place of mapData" (mouseover)="displayTagInfo($event)">
<div class="filter-name">{{place.name}}</div>
</div>
简短的回答是:
在您调用的函数中,您可以添加一个布尔变量来跟踪事件是否已经触发。
you need to initialize the variable inside the contructor of the
component you want to track it in.
function displayTagInfo(event){
if (this.tagInfoDisplayHasBeenFired) {
return;
}
this.tagInfoDisplayHasBeenFired = true
//Your code
}
在最初为 false 的 mapData 数组对象中放置一个键 hovered = false
,因此对于每个元素,您 hovered = false
将对象传递给特定位置 displayTagInfo($event,place)
<div *ngFor="let place of mapData" (mouseover)="displayTagInfo($event,place)">
<div class="filter-name">{{place.name}}</div>
</div>
在 .ts 中
displayTagInfo(event,place){
if(!place.hovered){
//Do what you want to do, HERE
place.hovered = true;
}
}
这样您就可以将每个元素悬停一次...祝您好运:)
我正在使用 angular7。在我的应用程序中,我显示了一个地点列表。当我将鼠标悬停在任何一个地方时,我正在调用 ajax 函数将该值存储在数据库中。
但是当我将鼠标悬停在任何一个元素上时,该 ajax 函数会被调用多次。我只想调用该函数一次。
这是我的 angular 代码:
<div *ngFor="let place of mapData" (mouseover)="displayTagInfo($event)">
<div class="filter-name">{{place.name}}</div>
</div>
简短的回答是: 在您调用的函数中,您可以添加一个布尔变量来跟踪事件是否已经触发。
you need to initialize the variable inside the contructor of the component you want to track it in.
function displayTagInfo(event){
if (this.tagInfoDisplayHasBeenFired) {
return;
}
this.tagInfoDisplayHasBeenFired = true
//Your code
}
在最初为 false 的 mapData 数组对象中放置一个键 hovered = false
,因此对于每个元素,您 hovered = false
将对象传递给特定位置 displayTagInfo($event,place)
<div *ngFor="let place of mapData" (mouseover)="displayTagInfo($event,place)">
<div class="filter-name">{{place.name}}</div>
</div>
在 .ts 中
displayTagInfo(event,place){
if(!place.hovered){
//Do what you want to do, HERE
place.hovered = true;
}
}
这样您就可以将每个元素悬停一次...祝您好运:)