html - HostListener OnClick 有时只工作
问题描述
在尝试在 Angular 中创建下拉框时,我遇到了一些不均匀的结果(我正在关注这些示例)。这是我的代码:
html
``` <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down"></i> </button>
<div id="eqLocDD" class="dropdown-content" *ngIf="showEQDD">
<option *ngFor="let e of eqLoc" class="option" (click)="ddClick(e)">{{e.Loc}}
</option>
</div>```
ts
if (event.target == document.getElementById("eqLocButton")) {
console.log("button clicked");
} else { //hide the drop down box, as a click has occurred outside the box
this.showEQDD = false;
console.log("button did NOT get clicked");
}
}
eqLocationDrop() { //show the drop down div
this.showEQDD = true;
}
ddClick(e) { // on click of an item in the drop down menu - get the data and hide the drop down
console.log(e)
this.showEQDD = false;
}
对此进行测试,当我单击下拉按钮之外的任何位置时,我得到“未单击按钮”;但是,当单击下拉按钮时,它似乎会按预期随机工作,然后立即停止工作,没有明显的模式。当它运行正常时,它永远不会被关闭然后立即重新打开。我是否没有执行 if() 来检查按钮是否被正确单击?似乎 event.target 是随机变化的。
解决方案
答案很简单——我尝试在控制台记录 event.target 对象,我了解到我有时会单击按钮,有时会单击按钮的图标。我曾认为该图标天生就是按钮的一部分,但显然它算作自己的对象,因此会使下拉菜单停止工作。我能够将一些文本放入此按钮并执行此操作:
html
<button id="eqButton" ><p id="v">V</p></button>
ts
if(event.target == document.getElementById("eqButton") || event.target == document.getElementById("v")) {
} else {
this.showEDD = false;
}
推荐阅读
- java - 我如何知道一个数字是否包含在java中的另一个数字中?
- oracle - Oracle - 我应该如何通过使用 EAV(实体属性值)设计将字段值存储在表中的 Oracle 表查询加速页面加载?
- python - 在python中计算百分比错误时出错
- node.js - Auth0登录,添加本地存储管理用户访问
- python-3.x - 这段代码中有一个双新行,如何删除它
- r - 对于每个组,应用一个函数并在 R 中返回一个不同维度的对象
- c# - 扩展我的 ASP.NET Core Web API (EF Core) 以调用存储过程
- python - 除了 else 循环,我的 while true 尝试做错了什么
- python - 在 Python 2D 数组中交换两个索引
- vega-lite - Vega Lite 栏宽度调整大小