javascript - 在 JavaScript 中单击后更改类名称
问题描述
我正在使用 Angular 6 和 Bootstrap。我正在尝试在单击(以更改其大小)后使用document.getElementsByClassName
. 我已经使用*ngFor
. 单击它们后,coinDetails(coin,i)
功能开始工作。
现在,单击元素后它会增加大小(类更改为:)col-lg-2 col-md-2 col-sm-12 col-xs-12 resize
,并且在第二次单击同一元素后,它会减小大小(类更改为col-lg-3 col-md-3 col-sm-12 col-xs-12 resize
:),正如我想要的那样。
但是当我单击一个元素然后单击另一个(index
更改)时,第一个元素保持增加。
我不知道,如何检测变量是否index
改变。
也许截图会更好地解释它。在这种情况下,我在开始时点击了“LTC”框,然后点击了“STRAT”框。'STRAT' 增大了尺寸,但 'LTC' 保持放大,尽管它不再是活跃的。我希望这个“LTC”框在它停止活动后与“ZEC”或“BTE”大小相同。
coinDetails(coin, index) {
if (this.detailToggle[index]) {
this.detailToggle[index] = false;
this.col = document.getElementsByClassName("resize")[index];
this.col.className = "col-lg-2 col-md-2 col-sm-12 col-xs-12 resize";
} else {
this.col = document.getElementsByClassName("resize")[index];
this.col.className = "col-lg-3 col-md-3 col-sm-12 col-xs-12 resize";
this.detailToggle.fill(false);
this._data.getCoin(coin).subscribe(res => {
this.details = res["DISPLAY"][coin]["USD"];
this.detailToggle[index] = true;
this._data.getChart(coin).subscribe(res => {
let coinHistory = res["Data"].map(a => a.close);
setTimeout(() => {
this.chart[index] = new Chart("canvas" + index, {
type: "line",
data: {
labels: coinHistory,
datasets: [
{
data: coinHistory,
borderColor: "#3cba9f",
fill: false
}
]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItems, data) {
return "$" + tooltipItems.yLabel.toString();
}
}
},
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [
{
display: false
}
],
yAxes: [
{
display: false
}
]
}
}
});
}, 250);
});
});
}
}
解决方案
尽量避免在 Angular 上使用 DOM 操作,而是使用 ngClass ( https://angular.io/api/common/NgClass ),在你的 html 中你应该有这样的东西:
<div *ngFor="let coin of coins">
<div [ngClass]="coinStyle(coin.coinStatus)" (click)="coinDetails(coin, index) || coin.coinStatus=!coin.coinStatus">
</div>
</div>
在组件上,是这样的:
coinStyle(status): string {
if (status) {
return 'col-lg-2 col-md-2 col-sm-12 col-xs-12 resize';
} else {
return 'col-lg-3 col-md-3 col-sm-12 col-xs-12 resize';
}
}
并删除您的 coinDetails 函数上的 DOM 操作。
this.col = document.getElementsByClassName("resize")[index];
this.col.className = "col-lg-3 col-md-3 col-sm-12 col-xs-12 resize";
this.col = document.getElementsByClassName("resize")[index];
this.col.className = "col-lg-3 col-md-3 col-sm-12 col-xs-12 resize";
(那 4 行)。
Ps 很抱歉,但由于您没有分享您的 HTML,我无法为您提供更好的指南。
推荐阅读
- recursion - Church Turing Thesis 是否保证递归代码可以作为迭代实现来实现?
- python-3.x - Python:将输出导出到 Google 表格
- python - 如何让输入字段出现在 JupyterLab 中?
- python-3.x - 需要 Python 正则表达式替换帮助
- python - Google AttributeError:“str”对象没有“授权”属性
- python - 如何从另一个本地 Python 脚本调用互联网 Python 脚本
- ruby-on-rails - 使用跨站点 cookie 从 Chrome 扩展发布到 Rails API
- fastify - Fastify 按标题获取项目总是返回原始 JSON 为 null
- c# - 在 DotPeek 的帮助下,我如何查看异步状态机(引擎盖下的异步/等待)?
- asp.net-core - 如何使用 ActionResult 发送抽象类型的集合